Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ template argument limited to classes (not basic types)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()); 
    
};

Demo

C++17

template<class T> typename std::enable_if_t<!std::is_fundamental_v<T>> Function(const T& x) 
{ 
    SetString(x.GetString()); 
    
};

Demo

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());   
};

Demo

Here we’ve used trailing return type syntax to specify the return type of the function template.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading