I have the following code in C++:
struct A; struct B { B(){} template<typename T> B(T param){} }; I want the constructor template to be valid only when the typename T is convertible to the type A. What is the best way to accomplish this?
I have the following code in C++:
struct A; struct B { B(){} template<typename T> B(T param){} }; I want the constructor template to be valid only when the typename T is convertible to the type A. What is the best way to accomplish this?
You want to enable the constructor if T is convertible to A? Use std::enable_if and std::is_convertible:
template < class T, class Sfinae = typename std::enable_if<std::is_convertible<T, A>::value>::type > B(T param) {} This works by applying SFINAE; if T is not convertible to A, the substitution will fail and the constructor will be removed from the set of candidate overloads.
14.8.1/7 of the standard, I find your answer very good. Thanks.