Question

I looked around for a good solution to avoid code duplication on each spezialization of a template class.

Here is an example code:

template<class T>
class C
{
    int foo();
}

Now the definition for defaults:

template<class T>
C<T>::foo() { return 0; }

Now the spezailization for special templates

template<> C<int>::foo()    { ... do a lot of stuff and return n .... }
template<> C<double>::foo() { ... do a lot of stuff and return n .... }
template<> C<int>::foo()    { ... do a lot of stuff and return n .... }

Right now I have to duplicate the code for the spezailization. But in general it's the same code.

My questions is: What is the best solution to avoid code duplication here and how can I hide the implementation ? Maybe by using a noname-namespace or an impl-namespace ?

Kind regards, Peter

Was it helpful?

Solution

You can do as with any other class: extract the boilerplate code to another (private) function in the template class and call this one in your specializations.

template<class T>
class C
{
    int foo();

    void bar() { /* does lot of stuff ... */ }
};

template<> int C<int>::foo() { bar(); return n .... }
template<> int C<double>::foo() { bar(); return n .... }

and how can I hide the implementation ? Maybe by using a noname-namespace or an impl-namespace ?

It's not really possible to hide the implementation of template code, by means of having a compilation unit specific unnamed namespace.

If your intend mainly is to get a cleaner readable template header file, you can factor out the implementation to another included file. These are often named .tcc or .icc, there are samples for this technique in most of the c++ implementation standard header files.

OTHER TIPS

One way to avoid duplicating code is to use a base class to handle generic implementation:

template <class T>
class base_C
{
    void generic_foo(){...}
};

template <>
class C <SpecialType> : base_C<SpecialType>
{
    void foo()
    {
        SpecialType::custom_foo();
        base_C<SpecialType>::generic_foo();
    }
};

The idea begind this is to split foo into more generic parts and put them into base_C. With this each specialization of C::foo will have a minimal amount of custom code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top