Search code examples
c++templatescastingtypecasting-operator

To Check if a class can be typecast to another


If I have a template function

template<class T, class U>
T foo (U a);

How can I check If an object of class U can be type cast into an object T

That is If The class U has a member function

operator T(); // Whatever T maybe

Or the class T has a constructor

T(U& a); //ie constructs object with the help of the variable of type U

Solution

  • You could use std::is_convertible (since C++11):

    template<class T, class U>
    T foo (U a) {
        if (std::is_convertible_v<U, T>) { /*...*/ }
        // ...
    }
    

    Note that is_convertible_v is added since C++17, if your compiler still doesn't support it you could use std::is_convertible<U, T>::value instead.