部分模板专业化有什么问题? [英] What is wrong with partial template specialization?
问题描述
我正在编写一个带有一个类型参数和一个布尔值的模板化类,这是代码:
I am writing a templated class with one type paramenter and one boolean, here is the code:
template<class T, bool p = true>
class A
{
private:
T* ptr;
public:
A();
};
template<class T>
A<T,true>::A()
{
ptr = 0xbaadf00d;
}
int main()
{
A<int> obj;
A<int, false> o;
return(0);
}
我得到了这些编译错误:
And I am getting these compilation errors:
Error 1 error C3860: template argument list following class template name must list parameters in the order used in template parameter list tst.cpp 15
Error 2 error C2976: 'A<T,p>' : too few template arguments tst.cpp 15
我做错了什么? 还是出于某种原因而被禁止部分专门化非类型参数?
What am I doing wrong? Or is it for some reason forbidden to specialize non-type parameters partially?
如果同时在if语句中使用boolean参数,则会收到以下警告:
At the same time if I use the boolean parameter in an if statement, I'm getting this warning:
Warning 1 warning C4127: conditional expression is constant
所以我应该专门做这类事情...
So I am supposed to do specializations for this kind of things...
任何帮助将不胜感激! :)
Any help would be highly appreciated! :)
提前谢谢!!!!
推荐答案
您正在尝试部分地专门化方法.那是不允许的.您只能对整个班级进行部分专业化训练.专门化该类后,可以为部分专门化的类提供方法的非专门化定义.
You are trying to partially specialize a method. That is not allowed. You can only partially specialize the whole class. Once you have specialized the class, you can then provide a non-specialized definition of the methods for the partially specialized class.
以下是一些可能满足您要求的代码的示例:
Here is an example of some code that might do what you want:
template<class T, bool p = true>
class A
{
private:
T* ptr;
public:
A();
};
template <class T>
class A<T,true> {
private:
T* ptr;
public:
A();
};
template <class T>
class A<T,false> {
private:
T* ptr;
public:
A();
};
template<class T>
A<T,true>::A()
{
ptr = reinterpret_cast<T *>(0xbaadf00d);
}
template<class T>
A<T,false>::A()
{
ptr = 0;
}
int main()
{
A<int> obj;
A<int, false> o;
return(0);
}
这篇关于部分模板专业化有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!