Conditional (SFINAE) redefinition

I am trying to do this:

struct A { virtual int f() const { return 0; } }; template <typename T> struct B : A { template <typename U = T, typename std::enable_if<...some condition involving U...>::type> int f() const { return 1; } }; 

Caution, I cannot inherit class templates (use static overrides). Is this type of construct allowed and can a member of the template B :: f () override the member A :: f ()?

+6
source share
1 answer

Try the following:

 template <typename T, typename=void> struct B : A { ... }; temlate <typename T> struct B<T, typename std::enable_if<...some condition...>::type>: A { virtual int f() const override { return 1; } }; 

where we have two versions of B<T> for which the condition is true ( enable_if one), for which the condition is false (by default).

If you want to use the default reimplementation of B , you could even do this:

 template <typename T, typename=void> struct B : A { ... }; template <typename T> struct B<T, typename std::enable_if<...some condition...>::type>: B<T, bool> { virtual int f() const override { return 1; } }; 

where we inherit the β€œfalse” case in the β€œtrue” case. But for me this is a bit dirty - I would rather instead hack into the overall implementation in third place ( B_impl ). (This also allows you to statically state that the second argument is void in the first case B ).

+6
source

All Articles