Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading using template

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).

like image 964
Andy Avatar asked Mar 05 '23 05:03

Andy


2 Answers

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; 
}
like image 169
Caleth Avatar answered Mar 12 '23 17:03

Caleth


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.

like image 33
songyuanyao Avatar answered Mar 12 '23 17:03

songyuanyao