3

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?

2
  • Sorry,I mixed C# and C++, I am working in both languages and I got confused. I just edited the question in order to fix the code. Commented Mar 3, 2015 at 14:16
  • Be aware that MSVC2013 has issues with the best practice answers to this problem in my experience. Commented Mar 3, 2015 at 14:47

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The 2nd template argument doesn't really need a name. But it is good
@BЈовић I know, but I generally use precisely this name as a bit of inline documentation.
In conjunction with the note 14.8.1/7 of the standard, I find your answer very good. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.