Reputation: 1209
Given the following class template, is there any way to have the field a
to be the same across all specializations (i.e. A<int>::a
is the same lvalue as A<std::string>::a
)?
template<class T>
class A final {
private:
static int a;
};
Upvotes: 1
Views: 74
Reputation: 1209
Thank you to those of you who suggested a non-templated base class. A similar solution that I found that removes the issue of an API consumer inheriting from the base class is to have it as a final class with the templated class declared as a friend:
class A_Data final {
private:
static int a;
template<class T>
friend class A;
};
template<class T>
class A final {
};
Upvotes: 1
Reputation: 302708
Simply inherit (privately) from a non-template and move the static
there:
class ABase {
protected:
static int a;
};
int ABase::a;
template<class T>
class A final : private ABase
{ };
Upvotes: 4