关于c ++:有关模板专业化和结果代码重复的问题

A Question on Template Specialization and the Resulting Code Duplication

为了专门化一个类模板,即使必须基本保持不变,也必须在底层基础模板(即非专业类模板)中重新定义所有成员函数。 有什么可以避免这种代码重复的公认方法和"最佳实践"?

谢谢。


您可以有选择地对成员进行完全专业化:

1
2
3
4
5
6
7
8
template<int N>
struct Vector {
    int calculate() { return N; }
};

// put into the .cpp file, or make inline!
template<>
int Vector<3>::calculate() { return -1; }

您将进行完全专业化。 意味着您不能部分地将其专门化:

1
2
3
4
5
6
7
8
template<int N, int P>
struct Vector {
    int calculate() { return N; }
};

// WROOONG!
template<int N>
int Vector<N, 3>::calculate() { return -1; }

如果需要,可以使用enable_if:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<int N, int P>
struct Vector {
    int calculate() { return calculate<p>
(); }
private:
    // enable for P1 == 3
    template<int P1>
    typename enable_if_c<P1 == P && P1 == 3, int>::type
    calculate() { return -1; }

    // disable for P1 == 3
    template<int P1>
    typename enable_if_c<!(P1 == P && P1 == 3), int>::type
    calculate() { return N; }
};

另一种方法是像Nick推荐的那样将您的东西拆分(将常见的东西分为基类,将专门的东西分为派生类)。

我通常会采用第二种方法。 但是如果我不需要部分地专门化功能,那么我更喜欢第一个。


通常会在这种情况出现时使用基类。 即:将通用功能放在基类中,并从基类派生模板类,然后仅使用不同的功能来专门化派生类。