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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With