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?
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
}
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?
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