mercredi 1 avril 2015

Why does constexpr static member (of type class) require a definition?

==> See the full snippet code and compilation on coliru.


I have a LiteralType class filling constexpr requirements:



struct MyString
{
constexpr MyString( char const* p=0, int s=0 ) : ptr(p), sz(s) {}
constexpr char const* data() const { return ptr; }
constexpr int size() const { return sz; }

char const *ptr = 0;
int const sz = 0;
};


I use it as a constexpr static member variable:



struct Foo
{
int foo() { return str_.size(); }

constexpr static MyString str_{"ABC",3};
};

int main()
{
Foo bar;
return ! bar.foo();
}


But the linker says:

(Clang-3.5 and GCC-4.9)



undefined reference to `Foo::str_'


I have to define the constexpr static member!

(I do not specify the constructor parameters)



constexpr MyString Foo::str_;


However if the constexpr static member had been an int the member would not have to be defined outside the class definition. This is my understanding, but I am not sure...


Questions:



  • Why int does not need to be defined outside the class declaration but MyString requires this?

  • Is there a disadvantage to define a constexpr static member in a header file?

    (I provide my library as header files only)


Aucun commentaire:

Enregistrer un commentaire