Is it possible specify a template argument, that would never match to a basic type, such as an int? I’m heavily fighting ambiguities. So for example:
template<class T> void Function(const T& x) { SetString(x.GetString()); };
That would work only if there’s a method GetString in T, but if the compiler sees this function, it tries to uses it even if T is just int for example.
>Solution :
You can use std::enable_if as shown below:
C++14
//this function template will not be used with fundamental types
template<class T> typename std::enable_if<!std::is_fundamental<T>::value>::type Function(const T& x)
{
SetString(x.GetString());
};
C++17
template<class T> typename std::enable_if_t<!std::is_fundamental_v<T>> Function(const T& x)
{
SetString(x.GetString());
};
Method 2
We can make use of SFINAE. Here we use decltype and the comma operator to define the return type of the function template.
//this function template will work if the class type has a const member function named GetString
template <typename T> auto Function (T const & x) -> decltype( x.GetString(), void())
{
SetString(x.GetString());
};
Here we’ve used trailing return type syntax to specify the return type of the function template.