Nick Mertin
Nick Mertin

Reputation: 1209

Static member shared across template specializations

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

Answers (2)

Nick Mertin
Nick Mertin

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

Barry
Barry

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

Related Questions