在C++中,如果要部分地专门化模板类中的单个方法,则必须专门化整个类(例如,在模板专门化中使用带有多个模板参数的模板化类的单个方法中所述)
然而,当具有多个模板参数的较大模板类中,当它们中的每一个影响单个函数时,这变得令人厌烦.使用N个参数,您需要专门化2 ^ N次!
但是,使用C++ 11我认为可能有一个更优雅的解决方案,但我不知道如何处理它.也许不知怎的enable_if
?有任何想法吗?
我想写 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 …
Run Code Online (Sandbox Code Playgroud)