Reputation: 10539
suppose I have code like this:
template <class T>
class Something{
public:
int func1();
int func2();
T t;
int n = 0;
};
template <class T>
int Something<T>::func1(){
return t.value() * n;
}
template <class T>
int Something<T>::func2(){
return n;
}
In this case Something::func2()
does not really depends of template parameter T, so it can be compiled into the object file, instead of recompiled every time (this is compiler dependent and can or can not be true).
Second, you still need to type template <class T> int Something<T>::func2()
.
is there a way to simplify the boilerplate code?
Upvotes: 4
Views: 1408
Reputation: 1384
In this case Something::func2() does not really depends of template parameter T, so it can be compiled into the object file, instead of recompiled every time (this is compiler dependent and can or can not be true).
No. func2 is a method of class, and since Something<int>
and Something<double>
are two different classes, their code should be compiled.
What you can do is extract method from the class, to a separate method or a base class, but in total, I think you shouldn't do that.
Upvotes: 3
Reputation: 40070
Object Oriented Programming is here to help you! Make Something<T>
inherit from an untempletized class SomethingBase
:
#include <iostream>
struct SomethingBase
{
int un_templatized();
};
int SomethingBase::un_templatized()
{
return 42;
}
template <class T>
struct Something : SomethingBase
{
T templetized(T t)
{
return t;
}
};
int main()
{
Something<double> s;
std::cout << s.un_templatized() << std::endl;
std::cout << s.templetized(3.14) << std::endl;
}
Upvotes: 1