【问题标题】:static member specialization of templated child class and templated base class模板化子类和模板化基类的静态成员特化
【发布时间】:2012-07-11 09:02:46
【问题描述】:

我正在尝试创建一个从另一个模板类(此处为 A)继承的模板类(此处为 C)并执行静态成员特化(此处为 int var),但我无法获得正确的语法(如果有可能

#include <iostream>

template<typename derived>
class A
{
    public:
        static int var;
};

//This one works fine
class B
    :public A<B>
{
    public:
        B()
        {
            std::cout << var << std::endl;
        }
};
template<>
int A<B>::var = 9;

//This one doesn't works
template<typename type>
class C
    :public A<C<type> >
{
    public:
        C()
        {
            std::cout << var << std::endl;
        }
};
//template<>
template<typename type>
int A<C<type> >::var = 10;

int main()
{
    B b;
    C<int> c;
    return 0;
}

我举了一个与非模板类(此处为 B)一起使用的示例,并且我可以获得 var 的静态成员特化,但对于 C 则不起作用。

这是 gcc 告诉我的:

test.cpp: In constructor ‘C<type>::C()’:
test.cpp:29:26: error: ‘var’ was not declared in this scope
test.cpp: At global scope:
test.cpp:34:18: error: template definition of non-template ‘int A<C<type> >::a’

我使用的是 gcc 版本 4.6.3,感谢您的帮助

【问题讨论】:

    标签: c++ templates static specialization


    【解决方案1】:

    您可以通过编写this-&gt;var 来提示编译器var 是一个成员变量。

    你不能写一个模板来定义模板特化A&lt;C&lt;type&gt;&gt;的静态成员;当您定义一个静态成员时,您正在保留存储空间,但编写模板部分特化并不会告诉编译器要为哪些完整特化保留存储空间。你能做的最好的就是写

    template<>
    int A<C<int> >::var = 10;
    

    另一种方法是使用通过模板函数访问的函数级静态:

    template<typename T> class A {
        static int &var() { static int var; return var; }
    };
    

    【讨论】:

    • “我不认为有任何方法可以部分特化模板类的静态成员”??问题是什么?静态成员的类型可以以作者想要的任何方式取决于模板的参数...(接近投票。请修复此问题)
    • @KirillKobelev 措辞不当;问题是定义静态成员(只能为完全专业化完成)。请看一看。
    • 现在好多了。谢谢。
    【解决方案2】:

    我建议您在父类中使用枚举并将子类的值设置为父类的模板参数。对于 C 类来“看到”var,它可以被限定。见下文:

    #include <iostream>
    using namespace std;
    
    template<typename Child, int i = 0> // 0 is the default value
    class A
    {
        public:
            enum { var = i };
    };
    
    class B
        :public A<B>   // define the value or var here
    {
        typedef A<B> Parent;
    public:
        B()
        {
            cout << Parent::var << endl; // Parent:: here IS NOT necessary, just for uniformity's sake
        }
    };
    
    template<typename type>
    class C
        :public A<C<type>, 200>  // define the value of var here
    {
        typedef A<C<type>, 200> Parent;
    public:
        C()
        {
            cout << Parent::var << endl; // Parent:: here IS necessary
        }
    };
    
    
    int main()
    {
        cout << B::var << endl;
        cout << C<int>::var << endl;
        cout << C<char>::var << endl;
    }
    

    【讨论】:

    • 我有一组模板化或非模板化的类(这里的“类型”),这些类必须有一个静态成员,所以我使用一个声明这个静态成员的基类(和更多的东西)和静态成员专业化我在子类中定义它。但是对于模板类(如示例中),这不起作用:/
    • 我明白了,我修改了我的答案以解决你想要做的事情。
    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多