Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid code duplication on multiple c++ template spezialization [duplicate]

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

like image 454
Peter Avatar asked Mar 20 '23 00:03

Peter


1 Answers

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.

like image 188
πάντα ῥεῖ Avatar answered Apr 29 '23 14:04

πάντα ῥεῖ