C ++专业化模板类函数而不复制代码 [英] C++ specialize template class function without duplicating code
本文介绍了C ++专业化模板类函数而不复制代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写5个不同的类,每个类都有很多成员函数,除了一个,这是每个类都是特殊的。我可以写这个避免代码重复吗?
I want to write 5 different classes, each of which has many member functions which are exactly the same, except of one, which is special for each class. Can I write this avoiding code duplication?
注意,
Aleksejs
Regards, Aleksejs
我的代码的版本,它抛出错误:
Below is a very shortened version of my code, which throws the error:
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;
}
推荐答案
,例如:
template <int cl, int dim>
class impl_prototype
{
int g(int x, std::integral_constant<int, 1>) { return cl + 3 * x; }
template <int I>
int g(int x, std::integral_constant<int, I>) { return cl + 1 * x; }
public:
int f(int x) { return cl + 2 * g(x); }
int g(int x) { return g(x, std::integral_constant<int, dim>());}
};
这篇关于C ++专业化模板类函数而不复制代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文