1

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;
};
Nick Mertin
  • 1,149
  • 12
  • 27

2 Answers2

4

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 
{ };
Barry
  • 286,269
  • 29
  • 621
  • 977
1

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 {
};
Nick Mertin
  • 1,149
  • 12
  • 27