Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to acces static member of templated class without template arguments

I have this code:

#include <iostream>

template <typename T>
class Test {
public:

    // Some code...

    static int member;
};

int main()
{
    std::cout << Test::member;
}

This of course doesn't work, because penultimate line is missing template arguments for Test.
But since member doesn't depend on T, i want to make it accessible without giving template arguments.

Is there some way to do it?

like image 569
FireFragment Avatar asked Jan 26 '26 21:01

FireFragment


2 Answers

If you declare a static member inside a class template Test, then there is a separate copy of the static member for each specialization (i.e. concrete type produced from the Test template). That is, Test<int>::member is a different object from Test<char>::member and so on. That's why you need to specify which one you mean.

To ensure that there is only one copy of member shared between all the Test specializations, you can move member into a non-template base class:

struct TestBase {
    static int member;
}

template <typename T>
class Test : public TestBase {
    // ...
};

int main() {
    // do something with TestBase::member
}
like image 79
Brian Bi Avatar answered Jan 28 '26 15:01

Brian Bi


There is not one, but many static variables named member. Which one would Test::member refer to? It doesn't make sense, so it's not allowed.

Test<int>::member = 42;
Test<short>::member = 13;

std::cout << Test::member << '\n';  // what should this print?
like image 34
Ayxan Haqverdili Avatar answered Jan 28 '26 14:01

Ayxan Haqverdili