【问题标题】:Initializing static member of nested templated class during nested template specialization?在嵌套模板专业化期间初始化嵌套模板类的静态成员?
【发布时间】:2023-03-19 17:50:01
【问题描述】:

这是我的问题:

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

如何正确初始化?

【问题讨论】:

    标签: c++ templates static


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 嗨 ildjarn,将您的代码粘贴到 Visual Studio 中,我收到以下错误:error C2906: 'int Outer::Inner::count' : explicit specialization需要'模板'你能解释一下吗?
    • @codekiddy:我在 VC++ 2010 SP1 中测试了这个确切的代码(加上#include &lt;iostream&gt;),没有出现错误。它也适用于GCC 4.3.4GCC 4.5.1。你用的是什么版本的VC++? (并且错误消息肯定意味着您以某种方式更改了我的代码,因为它抱怨的是 Outer&lt;T&gt;::Inner&lt;bool&gt;::count 而不是 Outer&lt;bool&gt;::Inner&lt;bool&gt;::count。)
    • 使用 Visual Studio 11 Beta 平台工具集 V110 :)
    • @codekiddy :对不起,我没有安装那个。无论哪种方式,这里显示的代码都是正确的;我怀疑您确实以某种方式对其进行了修改。 ;-]
    • 不,我没有修改代码,这可能是 VS Beta 11 中的一个错误,我现在要下载 VS 2010 并测试它,因为我想了解这一点。谢谢你的帮助!
    【解决方案2】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      相关资源
      最近更新 更多