static constexpr member of same type as class being defined

后端 未结 3 1736
故里飘歌
故里飘歌 2020-11-29 04:17

I would like a class C to have a static constexpr member of type C. Is this possible in C++11?

Attempt 1:

struct Foo {
    constexpr Foo() {}
    sta         


        
3条回答
  •  一整个雨季
    2020-11-29 04:58

    An update on Richard Smith's answer, attempt 3 now compiles on both GCC 4.9 and 5.1, as well as clang 3.4.

    struct Foo {
      std::size_t v;
      constexpr Foo() : v(){}
      static const Foo f;
    };
    
    constexpr const Foo Foo::f = Foo();
    
    std::array a;
    

    However, when Foo is a class template, clang 3.4 fails, but GCC 4.9 and 5.1 still work ok:

    template < class T >
    struct Foo {
      T v;
      constexpr Foo() : v(){}
      static const Foo f;
    };
    
    template < class T >
    constexpr const Foo Foo::f = Foo();
    
    std::array::f.v> a; // gcc ok, clang complains
    

    Clang error :

    error: non-type template argument is not a constant expression
    std::array::f.v> a;
                    ^~~~~~~~~~~~~~~~~~~~~
    

提交回复
热议问题