Question about template specialization and code duplication

To specialize a class template, you must redefine all member functions in the base base template (i.e., the non-specialized class template), even if they are expected to remain largely unchanged. What are some of the accepted methods and “best practices” to avoid code duplication?

Thanks.

+5
source share
2 answers

You can fully customize an element:

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

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

You are fully specialized. This means that you cannot specialize it privately:

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

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

If you need it, you can use 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; }
};

, ( ), .

. , .

+10

, . ..: , .

+4

All Articles