模板类中模板化成员函数的特化
我有一个带有模板化成员函数的模板化类
template<class T>
class A {
public:
template<class CT>
CT function();
};
现在我想以两种方式专门化模板化成员函数。首先是与类具有相同的类型:
template<class T>
template<> // Line gcc gives an error for, see below
T A<T>::function<T>() {
return (T)0.0;
}
其次是 bool 类型:
template<class T>
template<>
bool A<T>::function<bool>() {
return false;
}
这是我尝试测试它的方式:
int main() {
A<double> a;
bool b = a.function<bool>();
double d = a.function<double>();
}
现在 gcc 为我提供了上面标记的行:
error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialize
所以 gcc 告诉我,我必须专门化 A,如果我想要专门化功能,对吗? 我不想那样做,我希望外部类的类型是开放的...
最终的答案是:不可能吗?或者有什么办法吗?
I have a templated class with an templated member function
template<class T>
class A {
public:
template<class CT>
CT function();
};
Now I want to specialize the templated member function in 2 ways. First for having the same type as the class:
template<class T>
template<> // Line gcc gives an error for, see below
T A<T>::function<T>() {
return (T)0.0;
}
Second for type bool:
template<class T>
template<>
bool A<T>::function<bool>() {
return false;
}
Here is how I am trying to test it:
int main() {
A<double> a;
bool b = a.function<bool>();
double d = a.function<double>();
}
Now gcc gives me for the line marked above:
error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialize
So gcc is telling me, that I have to specialize A, if I want to specialize function, right?
I do not want to do that, I want the type of the outer class to be open ...
Is the final answer: it is not possible? Or is there a way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这就是问题所在:
如果不专门化班级,就无法专门化成员。
您可以做的是将
function
中的代码放在一个单独的类中并对其进行专门化,就像 basic_string 依赖于单独的 char_traits 类一样。然后,非专用函数可以调用特征类中的助手。Yes, this is the problem:
You cannot specialize a member without also specializing the class.
What you can do is put the code from
function
in a separate class and specialize that, much like basic_string depends on a separate char_traits class. Then then non-specializedfunction
can call a helper in the traits class.如果更改实现,则可以使用重载。
简单又容易:)
You can use overload, if you change the implementation.
Simple and easy :)