C++ 特化模板类函数,无需重复代码

Ale*_*ins 5 c++ templates class function partial-specialization

我想写 5 个不同的类,每个类都有许多完全相同的成员函数,除了一个,每个类都是特殊的。我可以写这个避免代码重复吗?

问候, 阿列克谢

下面是我的代码的一个非常缩短的版本,它引发了错误:

template_test.cpp:15:35: error: invalid use of incomplete type ‘class impl_prototype<cl, 1>
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
using namespace std;

template <int cl, int dim>
class impl_prototype {
public:
  impl_prototype() {}

  int f(int x) { return cl + 2 * g(x); }
  int g(int x) { return cl + 1 * x;}

};

template <int cl>
int impl_prototype<cl, 1>::g(int x) { return cl + 3 * x; }

int main ()
{
  impl_prototype<0, 0> test_0;
  impl_prototype<0, 1> test_1;


  cout << test_0.f(5) << " " << test_0.g(5) << std::endl;
  cout << test_1.f(5) << " " << test_1.g(5) << std::endl;


  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Tem*_*Rex 3

类模板的成员函数可以显式特化,但不能部分特化。

只需创建一个可以部分专业化的辅助函数对象:

#include <iostream>
using namespace std;

template<int cl, int dim>
struct g_impl
{
  int operator()(int x) { return cl + 1 * x;}    
};

template<int cl>
struct g_impl<cl, 1>
{
  int operator()(int x) { return cl + 3 * x; }    
};
Run Code Online (Sandbox Code Playgroud)

然后调用该帮助程序(临时函数对象将被优化掉):

template <int cl, int dim>
class impl_prototype 
{
public:
  impl_prototype() {}

  int f(int x) { return cl + 2 * g(x); }
  int g(int x) { return g_impl<cl, dim>()(x); }
};

int main ()
{
  impl_prototype<0, 0> test_0;
  impl_prototype<0, 1> test_1;


  cout << test_0.f(5) << " " << test_0.g(5) << std::endl;
  cout << test_1.f(5) << " " << test_1.g(5) << std::endl;


  return 0;
}
Run Code Online (Sandbox Code Playgroud)

实例