Well, you define the first three static constant variables, and then define them as constexpr. Since constexpr static member must be complete, it cannot be within the class itself. Your code should look like this:
class foo { int _x; public: constexpr foo(int x) : _x(x) {} constexpr int x() const { return _x; } }; constexpr foo a = foo{1}, b = foo{2}, c = foo{1};
If you still want to have foo as a static member, you can do this little trick:
class foo { int _x; constexpr foo(int x) : _x(x) {} struct constants; public: constexpr int x() const { return _x; } }; struct foo::constants { constexpr static foo a = foo{1}, b = foo{2}, c = foo{1}; };
Now why is the link error?
There, this little rule is called the Unified Definition Rule, which says that there can be any number of declarations, but one definition for all compilation units. According to your piece of code that you included in your question, it looks like you are defining your static member in your header. If there are two compilation units, including your title, you are breaking the rule. With my sample code above, you should no longer have this error, but instead: there is no definition. the constexpr value can be used at compile time, but will not be used at run time. To do this, you must declare this in a .cpp file:
#include "foo.h" constexpr foo foo::constants::a; constexpr foo foo::constants::b; constexpr foo foo::constants::c;
Now your three static variables are correctly declared and defined.
source share