I have a template class with a static const member:
template <class T>
class A
{
public:
A(T val) : t(val) {}
static const int VALUE = 5;
T t;
};
Let's say that somewhere in my code, I'm instantiating it using types int, char, and long. Now I want to access VALUE:
int main()
{
int i1 = A<int>::VALUE;
int i2 = A<char>::VALUE;
int i3 = A<long>::VALUE;
return 0;
}
Aren't all of the above identical ways to access the same thing? In cases like this, do others just choose a random type? Is there any way to avoid specifying the type?
The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .
So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.
1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.
These are all numerical constants, sharing the same value, but belonging to different name spaces. So you can't avoid specifying the enclosing class (by instantiating the template), even though it's not really needed.
You can, however, move the static const
definition into a class that A<T>
will inherit from:
class A_Consts
{
static const int VALUE = 5;
...
};
template<typename T>
class A : public A_Consts
{
...
};
Or, move the constant defintion outside the class, and enclose them both in a namesapce. Which seems like the better solution IMHO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With