Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类中模板成员函数的特殊化_C++_Template Specialization - Fatal编程技术网

C++ 模板类中模板成员函数的特殊化

C++ 模板类中模板成员函数的特殊化,c++,template-specialization,C++,Template Specialization,我有一个带有模板成员函数的模板类 template<class T> class A { public: template<class CT> CT function(); }; 所以gcc告诉我,如果我想专门化函数,我必须专门化A,对吗? 我不想这样做,我希望外部类的类型是开放的 最后的答案是:这是不可能的吗?还是有办法?是的,这就是问题所在: error: enclosing class templates are not explicitly sp

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

template<class T>
class A {
public:
    template<class CT>
    CT function();
};
所以gcc告诉我,如果我想专门化函数,我必须专门化A,对吗? 我不想这样做,我希望外部类的类型是开放的


最后的答案是:这是不可能的吗?还是有办法?

是的,这就是问题所在:

error: enclosing class templates are not explicitly specialized 
如果不专门化类,则不能专门化成员


所能做的就是将
函数中的代码放到一个单独的类中,并对其进行专门化,就像basic_字符串依赖于一个单独的char_类一样。然后,非专门化的
函数可以调用traits类中的助手。

如果更改实现,可以使用重载

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; }
};
模板
福班
{
公众:
模板
CT函数(){return helper((CT*)0);}
私人:
模板
CT助手(CT*);
T助手(T*){return(T)0.0;}
bool助手(bool*){return false;}
};
简单易用:)

可能重复的
int main() {
    A<double> a;
    bool b = a.function<bool>();
    double d = a.function<double>();
}
error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialize
error: enclosing class templates are not explicitly specialized 
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; }
};