模板化类中模板成员函数的专门化 [英] Specialization of templated member function in templated class

查看:221
本文介绍了模板化类中模板成员函数的专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有模板成员函数的模板类

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;
}

第二个类型为bool:

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>();
}

现在gcc给我上面标记的行:

Now gcc gives me for the line marked above:

error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialize

所以gcc告诉我,我必须专门化A,如果我想专门化功能,对吗?
我不想这样做,我想要外部类的类型打开...

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?

推荐答案

是的,这是问题:

error: enclosing class templates are not explicitly specialized 

你可以 / code>在一个单独的类和专门化,很像basic_string依赖于一个单独的char_traits类。然后非专门函数可以调用traits类中的帮助器。

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-specialized function can call a helper in the traits class.

这篇关于模板化类中模板成员函数的专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆