在嵌套模板专用化期间初始化嵌套模板类的静态成员

Initializing static member of nested templated class during nested template specialization?

本文关键字:嵌套 静态成员 初始化 专用      更新时间:2023-10-16

这是我的问题:

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    private:
        static int count;
    };
    static int code;
    void print() const
    {
        std::cout << "generic";
    }
};
template<>
template<>
class Outer<bool>::Inner<bool> 
{
    static int count;
};
template<>
template<>
int Outer<bool>::Inner<bool>::count = 4; // ERROR

如何正确初始化它?

完全专用的模板实际上不再是模板,因此您的定义应该只是:

int Outer<bool>::Inner<bool>::count = 4;

完整地说,所有定义都已到位,您的代码应如下所示:

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    private:
        static int count;
    };
    static int code;
    void print() const
    {
        std::cout << "generic";
    }
};
template<typename T>
int Outer<T>::code = 0;
template<typename T>
template<typename U>
int Outer<T>::Inner<U>::count = 0;
template<>
template<>
class Outer<bool>::Inner<bool> 
{
    static int count;
};
int Outer<bool>::Inner<bool>::count = 4;

若要为每个内部模板类实例获取一个静态成员,可以使用单独的模板类作为替代方法。

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    };
};
template <typename T>
struct InnerStatic
{
  static int count;
};
template <typename T>
int InnerStatic<T>::count = 4;
int main(int argc, char** argv)
{
  std::cout << InnerStatic<Outer<int>::Inner<int>>::count << std::endl;
  return 0;
}