Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const members of template classes

Tags:

c++

templates

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?

like image 600
user987280 Avatar asked Dec 27 '12 23:12

user987280


People also ask

Can a template function be static?

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> .

Can we use const with static?

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.

What is the syntax of template class?

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.


1 Answers

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.

like image 173
StoryTeller - Unslander Monica Avatar answered Oct 20 '22 01:10

StoryTeller - Unslander Monica