CRTP compiling error

后端 未结 2 1588
予麋鹿
予麋鹿 2021-01-14 02:46

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

template 
struct CRTP {
    static constexpr int num = Deriv         


        
相关标签:
2条回答
  • 2021-01-14 03:37

    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

    0 讨论(0)
  • 2021-01-14 03:41

    The problem is here:

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

    At the time of the instantiation of CRTP<A>, A isn't a complete class yet, so you can't actually access static members of it.

    One workaround is to pass in num as a separate template argument:

    template <typename Derived, int N>
    struct CRTP {
        static constexpr int num = N;
    };
    
    struct A : CRTP<A, 5> {
    
    };
    
    0 讨论(0)
提交回复
热议问题