静态成员跨模板特化共享

时间:2016-05-21 20:35:19

标签: c++ templates c++11

鉴于以下类模板,是否有任何方法可以使字段a在所有特化项中都相同(即A<int>::aA<std::string>::a的左值相同?)

template<class T>
class A final {
private:
    static int a;
};

2 个答案:

答案 0 :(得分:4)

只需从非模板继承(私下)并移动static

class ABase {
protected:
    static int a;
}; 

int ABase::a;

template<class T>
class A final : private ABase 
{ };

答案 1 :(得分:1)

感谢那些建议使用非模板化基类的人。我发现一个类似的解决方案,它消除了继承自基类的API使用者的问题,就是将它作为最终类,将模板化类声明为朋友:

class A_Data final {
private:
    static int a;

    template<class T>
    friend class A;
};

template<class T>
class A final {
};