Workaround for error: ??? cannot appear in a constant-expression

Jan Tusch
Thu May 20 14:20:00 GMT 2010

I observed the following issue with g++-4.3.4:

I can work around the restriction of initializing a static const integral 
class member with a non-constant expression.
This violates the standard and should be rejected by "-pedantic".
Correct me, if I'm wrong.

I cut down my code to the following (concededly a bit contrived) demo 

--- Example Code ---
template <class NT, int x>
struct X {
  static const NT VALUE;
template <class NT, int x>
const NT X<NT,x>::VALUE = static_cast<NT>(x);

struct FailingTruth {
  static const bool VALUE = X<double,1>::VALUE < X<double,1>::VALUE;

template <int x, int y>
struct Test {
  static const bool VALUE = X<double,x>::VALUE < X<double,y>::VALUE;

struct WorkingTruth {
  static const bool VALUE = Test<1,2>::VALUE;

template <bool B>
struct UseAsTemplateParamter {
  enum {
    VALUE = B

UseAsTemplateParamter<WorkingTruth::VALUE> object;

--- End Example Code ---

The compiler correctly complains with
error: ‘X<double, 1>::VALUE’ cannot appear in a constant-expression
in "FailingTruth".

However, when I encasulate the  very same condition using the Test template 
class, the "WorkingTruth" code is accepted by g++. I could even use 
WorkingTruth::VALUE as a non-type template parameter (see last line).

Am I missing something here, or does that really violate the standard.

Regards Jan.

PS: Don't get me wrong, I like this "feature", it is really useful, when doing 
some meta-programming involving floating-point constants :-)

More information about the Gcc mailing list