Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRTP compiling error

The following will compile with GCC 5.2 but not with Visual Studio 2015.

template <typename Derived>
struct CRTP {
    static constexpr int num = Derived::value + 1;
};

struct A : CRTP<A> {
    static constexpr int value = 5;
};

It complains that A does not have a member named value. How to fix the code so that it compiles on both compilers? Or is it illegal altogether?

like image 713
prestokeys Avatar asked Dec 24 '22 08:12

prestokeys


1 Answers

Try making it a constexpr function instead. The way you have it setup now attempts to access an incomplete type.
Since a templated member function will only be initialized upon first being used, type A will be fully defined by that point.

#include <iostream>

template <typename Derived>
struct CRTP {
    static constexpr int num() { return  Derived::value + 1; }
};

struct A : CRTP<A> {
    static constexpr int value = 5;
};

int main()
{
    std::cout << A::num();
    return 0;
}

See it live here

like image 88
StoryTeller - Unslander Monica Avatar answered Dec 26 '22 20:12

StoryTeller - Unslander Monica