user2023370
user2023370

Reputation: 11037

Class Template SFINAE via Inheritance

The s1 class template specialisation below only allows instantiations of s1 when using integral type template arguments.

template <typename, typename = void>
  struct s1;

template <typename T>
struct s1<T, std::enable_if_t<std::is_integral<T>::value>> { };

The following class template, s2, is similar; though it conditionally inherits privately from a trivial base class. What are the differences in functionality between s1 and s2?

struct Base { };

template <typename T>
struct s2 : private std::enable_if_t<std::is_integral<T>::value,Base> { };

Upvotes: 0

Views: 817

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

With s1 you can extend it with new specializations that cover more cases in distributed bits of code. SFINAE would kick in, and so long as only one specialization was valid, it would be chosen.

The expression tested in such specializations is arbitrary.

I could create an s1 specialization that accepts when T is floating point, or a complex type, or is an array.

For s2, only things that template pattern matching can prefer to a bare T can be used to create further matching specializations. There is no way to create an s2 specialization that accepts any floating point types, for example, but I could create one that accepts any pointers.

Upvotes: 3

Related Questions