Reputation: 10539
I have large template class with several methods etc.
Most of the methods do not use template parameter - Only few methods uses template parameter.
Is there a way to minimize boilerplate code?
template <class T>
class Something{
void method1();
void method2();
void method3();
};
template <class T>
void Something<T>::method1(){
T::use();
}
template <class T>
void Something<T>::method2(){
// do not use T at all, does not call method1()
}
template <class T>
void Something<T>::method3(){
// do not use T at all, does not call method1()
}
Any way I can avoid template <class T>
(in my real code template definition is way much bigger) ?
Upvotes: 1
Views: 764
Reputation: 45424
Put the non-template dependent methods in a base class.
class SomethingBase
{
protected:
void method2();
void method3();
};
template<typename T>
class Something
: SomethingBase
{
public:
void method1();
using SomethingBase::method2;
using SomethingBase::method3;
};
This does not change the functionality of the class, but is a bit more cumbersome than Neil Kirk's approach, which should be preferred if applicable.
If, as here, the only functionality of the base is to provide less specialised functionality for derived classes, all its members, including the constructors, should be protected
.
Upvotes: 3
Reputation: 21773
If only method1
uses the template parameter, only that function needs to be templated.
class Something
{
template<class T>
void method1()
{
T::use();
}
void method2();
void method3();
};
Note that this slightly changes the functionality of the class. It's now possible for an instance to be called with a variety of types on its method1
whereas before only 1 type was possible and had to be decided up front.
Upvotes: 1