S
struct foo{
static const int blah = 3;
}
...ist nur eine Deklaration von blah und keine Definition. Es wird also nirgens Speicher dafür angelegt. Für "konstante Ganzzahltypen" (integral types) wird aber eine "Initialisierung" in der in-class Deklaration erlaubt. Solange nur der Wert von blah benutzt wird und zB nicht die Adresse von blah benötigt wird, ist auch keine Definition von blah nötig.
Bei Dir soll value aber vom Typ double sein. Für double gilt die Ganzzahltypen-Sonderregel natürlich nicht.
Das folgende Programm wird gnädigerweise vom G++ (3.4.5) erfolgreich, auch ohne Linker-Fehler, übersetzt:
#include <iostream>
template<int Base, int Power>
struct powr
{
static const double value =
powr<(Base*Base),(Power/2)>::value
* powr< Base ,(Power%2)>::value;
};
template<int Base>
struct powr<Base,1>
{
static const double value = Base;
};
template<int Base>
struct powr<Base,0>
{
static const double value = 1.0;
};
template<int Base>
struct powr<Base,-1>
{
static const double value = 1.0/Base;
};
int main()
{
double const x = powr<2,3>::value;
std::cout << x << '\n';
}
Es ist aber nicht Standard-konform. Der Comeau C/C++ Online-Compiler sagt dazu folgendes:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions
"ComeauTest.c", line 6: error: a member of type "const double" cannot have an
in-class initializer
static const double value =
^
"ComeauTest.c", line 14: error: a member of type "const double" cannot have an
in-class initializer
static const double value = Base;
^
"ComeauTest.c", line 20: error: a member of type "const double" cannot have an
in-class initializer
static const double value = 1.0;
^
"ComeauTest.c", line 26: error: a member of type "const double" cannot have an
in-class initializer
static const double value = 1.0/Base;
^
4 errors detected in the compilation of "ComeauTest.c".
Recht hat er.
Warum schreibst Du nicht einfach std::pow(2,3)? Der GCC rechnet das, soweit ich weiß, trotzdem zur Compilezeit aus. Dieses Verhalten wird zwar nicht vom C++ Standard garantiert, zeichnet aber einen guten Compiler meiner Meinung nach aus.
Gruß,
SP
P.S: Ja, ich habe Informatik mit Schwerpunkt "Modelle & Algorithmen" studiert.