==> See the full snippet code and compilation on coliru.
I have a LiteralType class filling constexpr
requirements:
struct MyString
{
constexpr MyString(char const* p, int s) : 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 size() { return str_.size(); }
constexpr static MyString str_{"ABC",3};
};
int main()
{
Foo foo;
return ! foo.size();
}
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)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…