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

2024-04-22

我想编写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;
}

实例 http://coliru.stacked-crooked.com/a/e59255e599be1072

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++专门化模板类函数,无需重复代码 的相关文章

随机推荐