[英]Specialization of templated member function in templated class
I have a templated class with an templated member function我有一个带有模板成员 function 的模板 class
template<class T>
class A {
public:
template<class CT>
CT function();
};
Now I want to specialize the templated member function in 2 ways.现在我想以两种方式专门化模板化成员 function。 First for having the same type as the class:
首先与 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:现在 gcc 给了我上面标记的行:
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?所以gcc告诉我,我必须专攻A,如果我想专攻function,对吧? I do not want to do that, I want the type of the outer class to be open...
我不想那样做,我想打开外部 class 的类型...
Is the final answer: it is not possible?是最后的答案:不可能吗? Or is there a way?
或者有什么办法吗?
Yes, this is the problem:是的,这就是问题所在:
error: enclosing class templates are not explicitly specialized
You cannot specialize a member without also specializing the class.如果不专门化 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.您可以做的是将
function
中的代码放在单独的 class 中并专门处理它,就像 basic_string 依赖于单独的 char_traits class 一样。 Then then non-specialized function
can call a helper in the traits class.然后非专业化的
function
可以在特征 class 中调用助手。
You can use overload, if you change the implementation.如果您更改实现,则可以使用重载。
template <typename T>
class Foo
{
public:
template <typename CT>
CT function() { return helper((CT*)0); }
private:
template <typename CT>
CT helper(CT*);
T helper(T*) { return (T)0.0; }
bool helper(bool*) { return false; }
};
Simple and easy:)简单易行:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.