A third and likewise common variation to
static_assert
from Jarod42:s answer, and
- using
std::enable_if_t
as the type of a non-type template parameter defaulted to some value (template<..., std::enable_if_t<..., bool> = true>
) from NathanOliver's answer
is to use std::enable_if_t
as the default template argument to a type template parameter (as compared as the type of a non-type template parameter):
template<typename T,
typename = std::enable_if_t<std::is_base_of_v<A, T>>>
class X {};
this is somewhat briefer than using the non-type template parameter approach.
It comes with the drawback, however, that when used for function templates it cannot be combined with, say SFINAE-overloading two variations solely based on opposite results for a predicate:
// Not OK.
template<typename T,
typename = std::enable_if_t<std::is_base_of_v<A, T>>>
void foo(const T&) { /* some impl */ }
// Error: re-definition of foo
template<typename T,
typename = std::enable_if_t<!std::is_base_of_v<A, T>>>
void foo(const T&) { /* another impl */ }
as both overloads differ only in their default template arguments, which is not part of the function template's signature, they declare two different function templates with the same signature, which is illegal.
If we non-type template approach instead, this is not an issue:
// OK
template<typename T,
std::enable_if_t<std::is_base_of_v<A, T>>* = nullptr>
void foo(const T&) { /* some impl */ }
template<typename T,
std::enable_if_t<!std::is_base_of_v<A, T>>* = nullptr>
void foo(const T&) { /* another impl */ }