鉴于以下类模板,是否有任何方法可以使字段a
在所有特化项中都相同(即A<int>::a
与A<std::string>::a
的左值相同?)
template<class T>
class A final {
private:
static int a;
};
答案 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 {
};