Can I have a compile time constant instance of a class (as a member) in C++?
In C++, say I have a class Thing, I'd like it to include a const member of that type, something like:
class Thing
{
public:
Thing();
private:
static const Thing THING;
};
But I don't think this works as above. How can I do this?开发者_如何学Python
The following little program compiles and links using GCC 3.4.5 (MinGW):
class Thing
{
public:
Thing();
private:
static const Thing THING;
};
Thing::Thing()
{}
// We must instantiate the static variable somewhere, like inside 'Thing.cpp'
const Thing Thing::THING = Thing();
int main(int argc, char* argv[])
{
return 0;
}
I'm not sure what the standard says about this, but I don't see why it shouldn't work. It compiles fine on my gcc. Did you remember to instantiate the static object outside of the class declaration?
No. You can't.
As S.C.Madsen and int3 already posted, you can declare static const in class scope for any type, as long as it is properly defined (in the cpp file) and initialized, But it can't be a compile time constant.
Compile time constant is a constant you can use as template argument and as built in arrays' size. These constants may also be optimized better than run-time constants. Currently, AFAIK, only the built in numeric types may serve as compile time constants.
The reason, BTW, is that this constant should be evaluated at compile time (similarly to literals).
精彩评论