I'm trying to create static constexprs defined inside the class. I know about this question: static constexpr member of same type as class being defined, and method 3 works fine now.
However, I have a problem with the linker. It reports of duplicate symbols, probably because of the const to constexpr redefinition. Is there a way to accomplish this? I am using xcode 7.
The code I am trying is:
class foo{
int _x;
constexpr foo(int x) : _x(x) {}
public:
static const foo a, b, c;
constexpr int x() const { return _x; }
};
constexpr foo foo::a = foo(1), foo::b = foo(2), foo::c = foo(1);
Including this file in more than one place causes a linker error stating
3 duplicate symbols for architecture x86_64
I know this is the problem, because if I only include it once it works fine.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With