Home > other >  Type trait to identify classes derived from a CRTP class
Type trait to identify classes derived from a CRTP class

Time:02-01

I am looking to implement the function is_type_of_v, able to identify the templated instances of type Skill. Please, see the main function in source code below to fully understand the request. It is harder to explain by words than by code.

The solution should work in VS 2017 under c 17. The next link contains the example: https://godbolt.org/z/4x3xoh1Pb

#include <iostream>
#include <type_traits>

template<class T>
struct Base
{
private:
    constexpr Base() = default;
    friend T;
};

struct Derived1 : Base<Derived1>
{
};

struct Derived2 : Base<Derived2>
{
};

template<class T, class F, int... Ints>
struct Skill : T
{

};

int main()
{
    Skill<Derived1, std::equal_to<int>, 1, 2> object1;
    Skill<Derived2, std::equal_to<int>, 3> object2;
    Derived1 other;

    constexpr auto res1 = is_type_of_v<Skill, decltype(object1)>;//Must be true
    constexpr auto res2 = is_type_of_v<Skill, decltype(object2)>;//Must be true
    constexpr auto res3 = is_type_of_v<Skill, decltype(other)>;//Must be false
}

CodePudding user response:

For Skill, you can write something as

template <template <typename, typename, auto...> class, typename>
struct is_type_of : public std::false_type
{};

template <template <typename, typename, auto...> class C,
          typename T1, typename T2, auto ... Is>
struct is_type_of<C, C<T1, T2, Is...>> : public std::true_type
{};

template <template <typename, typename, auto...> class C, typename T>
constexpr auto is_type_of_v = is_type_of<C, T>::value;

so you can verify that

static_assert( true  == is_type_of_v<Skill, decltype(object1)> );
static_assert( true  == is_type_of_v<Skill, decltype(object2)> );
static_assert( false == is_type_of_v<Skill, decltype(other)> );

Unfortunately this solution works only for template-template parameters receiving a couple of typename, before, and a variadic list of values, after.

I don't think it's possible (C 17 but also C 20) a generic solution for a generic template-template parameter in first position.

And before C 17 (C 11 and C 14) is even worse, because you can't use auto... for values.

  •  Tags:  
  • Related