[英]static member specialization of templated child class and templated base class
我正在尝试从另一个模板化类(这里是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,感谢您的帮助
您可以通过编写this->var
来提示编译器var
是成员变量。
您不能编写模板来定义模板专业化A<C<type>>
的静态成员; 当您定义静态成员时,您要保留存储空间,但是编写模板部分专业化并不能告诉编译器要为其保留存储的全部专业化。 你能做的最好的就是写
template<>
int A<C<int> >::var = 10;
一种替代方法是使用通过模板函数访问的函数级静态变量:
template<typename T> class A {
static int &var() { static int var; return var; }
};
我建议您在父类中使用一个枚举,并将子类中的值设置为父类的模板参数。 为了使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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.