Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 594
WARhead Avatar asked Dec 19 '25 00:12

WARhead


1 Answers

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.

like image 190
songyuanyao Avatar answered Dec 21 '25 14:12

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!