模板化子类和模板化基类的静态成员专业化
问题描述:
我想从另一个模板化类(此处为A)继承并执行静态成员专门化(此处为int var)的模板化类(此处为C),但我不能得到正确的语法,这样做(如果可能的话模板化子类和模板化基类的静态成员专业化
#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,感谢您的帮助
答
可以提示编译器var
是通过编写this->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;
}
“我不认为有任何办法部分专门化模板类静态成员”?问题是什么?静态成员的类型可以取决于作者想要的任何方式模板的参数...(接近downvote。请修复此问题) – 2012-07-11 09:14:24
@KirillKobelev错误的措辞;问题是*定义*静态成员(只能为完整的专业化)。请看一下。 – ecatmur 2012-07-11 09:20:37
现在好多了。谢谢。 – 2012-07-11 09:22:32