c++ - 如何专门化模板类的某些成员?

标签 c++ templates template-specialization partial-specialization

代码:

template<class T>
struct A {
  void f1() {};
  void f2() {};

};

template<>
struct A<int> {
  void f2() {};
};


int main() {
  A<int> data;
  data.f1();
  data.f2();
};

错误:

test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'

基本上,我只想特化一个函数,而对其他函数使用通用定义。 (在实际代码中,我有很多我不想专门化的函数)。

如何做到这一点?谢谢!

最佳答案

考虑将公共(public)部分移动到基类:

template <typename T>
struct ABase
{
    void f1();
};


template <typename T>
struct A : ABase<T>
{
    void f2();
}  


template <>
struct A<int> : ABase<int>
{
    void f2();
};

您甚至可以在派生类中覆盖 f1。如果您想做一些更奇特的事情(包括能够从基类中的 f1 代码调用 f2),请查看 CRTP .

关于c++ - 如何专门化模板类的某些成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4955609/

相关文章:

c++ - 我如何在函数cpp中返回字符串

c++ - 在查找 namespace 名称期间可以考虑哪些其他名称,而不是 namespace 名称?

C++ 模板隐式使用

c++ - 错误 C2784 : Could not deduce template argument

c++ - 模板类专门针对模板类和其他类型

c++ - C++中构造函数的返回类型

c++ - 如何从 C++ 查询数据库表

c++ - C++ 模板中的 const 引用

c++ - 专门化嵌套模板

c++ - 通过 const 引用传递模板