【发布时间】:2014-08-04 13:08:02
【问题描述】:
我想写 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;
}
【问题讨论】:
-
它们可以有一个共同的基类吗?
-
继承和虚函数怎么样?
-
@JoachimPileborg 继承 + 帮助器的部分特化更惯用,在 OP 的代码中看不到
virtual。 -
这是this的完全相同的副本
标签: c++ function class templates partial-specialization