简体   繁体   中英

static const members of template classes

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM