关于模板专业化和结果代码复制的问题

Ash*_*Ash 5 c++ templates

要专门化类模板,必须重新定义底层基本模板中的所有成员函数(即非专用类模板),即使它们预计基本保持不变.有哪些可接受的方法和"最佳实践"可以避免此代码重复?

谢谢.

Joh*_*itb 10

您可以选择性地完全专门化成员:

template<int N>
struct Vector {
    int calculate() { return N; }
};

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

你做了一个完整的专业化.意思是你不能局部专门化它:

template<int N, int P>
struct Vector {
    int calculate() { return N; }
};

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

如果需要,可以使用enable_if:

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; }
};
Run Code Online (Sandbox Code Playgroud)

另一种方法是将你的东西(普通的东西分成基类,特殊的东西分成派生类)分开,就像Nick推荐的那样.

我通常采取第二种方法.但如果我不需要部分专门化功能,我更喜欢第一个.