I\'m trying to create static constexpr
s defined inside the class. I know about this question: static constexpr member of same type as class being defined, and metho
Well, you define first three static const variables and then you defines them as constexpr. Since constexpr static member must be complete, it cannot be in the scope of 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 desire 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};
};
Follow this if you're using C++14 and before. In C++17, all constexpr static data members are implicitly inline.
Now why the link error?
There's this little rule called the One Definition Rule, which states that there can be any number of declaration but one definition across all compilation units. By your code snippet you included in your question, it look like you are defining your static member in your header. If there's two compilation unit including your header, you break the rule. With my code example above you should not have this error anymore, but another one instead: there is no definition. the constexpr value might be used at compile time, but won't be usable at runtime. 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.