void.pointer
void.pointer

Reputation: 26365

Should static constexpr class member variables be defined even if they are not ODR-used?

Suppose the following class definition in a header file:

class foo
{
public:
    static float constexpr MY_VALUE{100.f};
};

In my CPP file, I have this:

float constexpr foo::MY_VALUE;

However, if foo::MY_VALUE is never ODR-used, should I define it? Does defining it when it isn't ODR-used hurt anything? Is it a good rule of thumb to always provide a definition like this for class static constexpr variables?

Upvotes: 3

Views: 547

Answers (1)

luk32
luk32

Reputation: 16070

This is a bit opinion based IMO, but trying to stay technical... from the definition you don't have to do it, unless it is ODR-used, so it seems trivial. Don't. Also, a user can always provide definition for the context they needs.

As for the rule of thumb, one can also refer to:

3.2 One definition rule. p3

A variable x whose name appears as a potentially-evaluated expression ex is odr-used unless x satisfies the requirements for appearing in a constant expression (5.19) and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion (4.1) is applied to e, or e is a discarded-value expression (Clause 5). [...]

Taken from c++14 draft.

So I would say: if you predict that your constant will be used in a non-const context I'd provide a definition for convenience. If not, then not. But it's a design decision one has to make.

Upvotes: 2

Related Questions