Reputation: 113
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).
Upvotes: 4
Views: 156
Reputation: 113
In C++20, it can be implemented with constraints and concepts:
template <class T>
concept IsIntegral = is_same_v<T, char>
|| is_same_v<T, int>
|| is_same_v<T, long>;
template <IsIntegral T>
void foo(T& arg) { ++arg; }
template <class T> requires IsIntegral<T>
void bar(T& arg) { ++arg; }
Upvotes: 0
Reputation: 173014
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.
Upvotes: 3
Reputation: 63152
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;
}
Upvotes: 4