Search code examples
c++compiler-errorsstatic-variablesinlining

C++: "(static const double variable) cannot appear in constant-expression"


In classA I've got:

static const double alias_var = classB::const_var;

Then in classB:

static const double const_var = 1000.;

But the compiler keeps telling me:

'classB::const_var' cannot appear in a constant-expression.

Why not? The funny thing is if I change classB::const_var from a double to an int, the errors go away.

I inlined these variables for optimization. I hope that using floating-points doesn't prevent the optimization.

I'm using GCC 5.4.0 in a Ubuntu 64-bit environment. I'm sure the fact I'm using Qt4 has nothing to do with it.

Edit: my best workaround is to have in classB:

static const int const_var_int = 1000;
static const double const var = const_var_int;

and then in classA (any everywhere else) assign const_var_int to my floating-points. It gets rid of the errors. I don't know if it's defeating the purpose or what other consequences there are.


Solution

  • Short answer: use constexpr instead of const.

    Long answer: there are special provisions in old C++03 which allow class members which are static integral constants be used in constant expressions. This provision does not apply to non-integral (doubles).

    With C++11, constexpr removed this limitation.