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?

PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
Raul Alonso
  • 453
  • 3
  • 13

1 Answers1

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455