Implement a type trait for a class template that is true for the actual class template and classes that inherit it

  c++, c++17, typetraits

I have a tuple-like class template like this

template <class... T>
struct Foo {}

Now I need to implement something like this

template <class T>
void bar (const T& t)
{
    if constexpr (IsFoo<T>::value)
        // treat it as Foo
    else
        // a generic solution
}

IsFoo can be implemented straightforward like this

template <class T>
struct IsFoo : std::false_type {}

template <class... T>
struct IsFoo<Foo<T...>> : std::true_type {}

Now, I also need IsFoo to be true in case the type passed is publicly derived from any instantiation of Foo, e.g.

struct Derived : public Foo<int, float> {}

should also be treated like a Foo in the first if constexpr branch above.

However, I can’t figure out how to properly implement a template specialisation of my IsFoo trait that would work when Derived is passed to it. But I’m sure Stackoverflow knows how to!

Source: Windows Questions C++

LEAVE A COMMENT