1

这是我的问题:

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

如何正确初始化它?

4

2 回答 2

6

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

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;
于 2012-05-03T18:32:16.993 回答
0

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

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;
}
于 2018-06-23T11:27:46.397 回答