I have the following functions:
void func1(int8_t input);
void func1(int16_t input);
void func1(int32_t input);
void func1(float input);
The implementation of the four functions is the same, except for some internal value that are in accordance with the input type (int8_t
, int16_t
, int32_t
or float
).
Currently I am creating the other three functions by copy-paste but this is quite tedious.
Is there any way so that I only write 1 function (for example, func1(int8_t input);
) and that at building time, the other three functions are created automatically?
Or in which this could work with no need of the other three functions? Any other solution is well appreciated.
Usage of template function is the solution for this problem:
template <typename T>
void func1(const T value)
{
// Do some stuff
}
If you need to use special internal value, which depends on input type, you can use auxiliary type traits like this:
template <typename T>
struct SomeTrait
{
static const int value = 10;
};
template <>
struct SomeTrait<float>
{
static const int value = 20;
};
template <typename T>
void func1(const T value)
{
std::cout << SomeTrait<T>::value << std::endl;
// Do some stuff
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments