C++专门化模板类函数而无需重复代码

标签 c++ function class templates partial-specialization

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

问候, 阿列克谢斯

下面是我的代码的一个非常简短的版本,它抛出了错误:

template_test.cpp:15:35: error: invalid use of incomplete type ‘class impl_prototype<cl, 1>

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

最佳答案

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

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

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

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

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

Live Example

关于C++专门化模板类函数而无需重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119444/

相关文章:

bash:如何从变量创建函数?

c++ - 为什么我的类(class)规模大于其成员的总和?

javascript - 将 JS 类转换为真正的类

c++ - 模拟3D游戏中的鼠标移动?

C++重载加法运算符来添加对象

c - 将数字分开然后求和的函数

C++ 未解析的外部符号

c++ - 将值分配给来自多个 int 类型的位集

c++ - 在头文件重新定义错误中包含 .cpp - 实现通用堆栈

python - 如何更新列表而不是删除以前的输入