Here are two overloading declarations of a function:
void fun(char& arg);
void fun(int& arg);
void fun(long& arg);
The definitions are doing the same job:
void fun(char& arg) { ++arg; }
void fun(int& arg) { ++arg; }
void fun(long& arg) { ++arg; }
How to declare and define the function once by using template, which accepts only int
, char
and long
types for the argument? Error should appear as soon as possible (before runtime) if the function is misused (e.g. a variable of double
type is passed).
You can just static_assert
in the body of the function with a bunch of std::is_same
template<typename T>
void fun(T& arg)
{
static_assert(
std::is_same_v<T, char> ||
std::is_same_v<T, int> ||
std::is_same_v<T, long>,
"bad call");
++arg;
}
You can apply SFINAE with std::enable_if
and std::is_same
.
template <typename T>
std::enable_if_t<std::is_same_v<T, int> ||
std::is_same_v<T, char> ||
std::is_same_v<T, long>>
fun(T& arg) { ++arg; }
For other types you'll get a no matching function for call error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With