OiO.lk Blog templates Access non-type template parameter of CRTP derived class from CRTP base class
templates

Access non-type template parameter of CRTP derived class from CRTP base class


In the following CRTP code, is there a simple way to access the non-type template parameter N in Base that is exposed by Derived?

template <typename TDerived>
struct Base
{
    int array[TDerived::NValue];
};

template <int N>
struct Derived : Base<Derived<N>>
{
    constexpr static int NValue = N;
};

int main()
{
    Derived<8> derived;
}

The VS2022 throws error: ‘NValue’: is not a member of ‘Derived<8>’

Do I have to use a separate trait struct?

The following code compiles, but the additional N seems redundant:

template <typename TDerived, int N>
struct Base
{
    int array[N];
};

template <int N>
struct Derived : Base<Derived<N>, N>
{
};

int main()
{
    Derived<8> derived;
}

Thanks!



You need to sign in to view this answers

Exit mobile version