Soweit ich weiß, können Sie nur statische const Mitglieder in der gleichen Zeile ihrer Deklaration if they are integral types initialisieren. Allerdings war ich noch in der Lage einige statische const zu initialisieren und verwenden verdoppelt:Falsche statische const Initialisierung, kompiliert und funktioniert
// compiles and works, values are indeed doubles
struct Foo1{
static const double A=2.5;
static const double B=3.2;
static const double C=1.7;
};
// compiles, but values are cast to int
struct Foo2{
static const int A=2;
static const int B=3;
static const double C=B/A; //becomes 1
};
// does not compile, Foo3::B cannot appear in a constant-expression
struct Foo3{
static const int A=2;
static const double B=3;
static const double C=A/B;
};
// does not compile, a cast to a type other than an integral or enumeration
// cannot appear in a constant-expression
struct Foo4{
static const int A=2;
static const int B=3;
static const double C=(double)A/B;
};
foo2 kompiliert aber foo2 :: C 1 wird, vielleicht wird es als int behandelt, wie es numerisch ist. Foo3 und Foo4 kompilieren nicht wie erwartet. Allerdings verstehe ich nicht, warum Foo1 sowohl kompiliert als auch korrekt funktioniert. Wird diese spezifische Verwendung akzeptiert? Liegt es an einer Optimierung? (Ich habe versucht mit -O1 und -O0)
Hinweis: GNU 5.2.0 mit cmake verwenden und den Standard auf C++ 98 setzen. Die Umstellung auf C++ 11 funktioniert einwandfrei (das heißt, kompiliert nicht und fragt, ob diese Mitglieder zu conexpr wechseln sollen).
Fügen Sie den '-pedantic' Schalter hinzu, dann gcc wird sich sogar über' Foo1' beschweren. http://melpon.org/wandbox/permlink/o35cpEXlgMedfvMT – dyp