Specialization of templated member function in templated class
我有一个带有模板成员函数的模板类
1 2 3 4 5 6 | template<class T> class A { public: template<class CT> CT function(); }; |
现在,我想以两种方式专门化模板化的成员函数。 首先具有与类相同的类型:
1 2 3 4 5 | template<class T> template<> // Line gcc gives an error for, see below T A< T >::function< T >() { return (T)0.0; } |
布尔型第二:
1 2 3 4 5 | template<class T> template<> bool A< T >::function<bool>() { return false; } |
这是我尝试测试的方式:
1 2 3 4 5 | int main() { A<double> a; bool b = a.function<bool>(); double d = a.function<double>(); } |
现在,gcc为我提供了上面标记的行:
1 2 | error: invalid explicit specialization before ‘>’ token error: enclosing class templates are not explicitly specialize |
所以gcc告诉我,如果我想专门研究函数,我必须专门研究A,对吗?
我不想这样做,我想打开外部类的类型...
最后的答案是:不可能吗? 还是有办法?
是的,这是问题所在:
1 | error: enclosing class templates are not explicitly specialized |
您不能不对课程进行专门化就不能对成员进行专门化。
您可以做的是将
如果更改实现,则可以使用重载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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; } }; |
简单容易:)