I was using std::vector in my program and now I made a realization that Eigen::VectorXd will reduce my task in great deal. So I shifted to using Eigen. But I don't want to change the program entirely so I thought of using Templates for some previously defined functions.
I'm new to C++ and template programming is little bit confusing I'm not able to think beyond the below program which is wrong.
using namespace Eigen;
template<class T>
T getvec(T& var)
{
T res;
res[0] = var[0]*3;
res[1]=var[1]*3;
res[2]=var[2]*3;
return res;
}
int main(){
std::vector<double> a(3,1);
Eigen::VectorXi b(3);
b.setOnes();
auto x= getvec(a);
auto y=getvec(b);
}
Is it possible to write a template function which can take std::vector or Eigen::VectorXd as paramters?
I am in need of a of function as below which can take both type.
std::vector<double> getTransform(std::vector<double>& vec)
{
std::vector<double> res;
res[0] = vec[0]*3.14;
...........
...........
return res;
}
Try this:
template <typename T>
T getTransform(const T& vec)
{
T res;
res.resize(vec.size());
for (size_t i = 0; i < size_t(vec.size()); ++i)
{
res[i] = vec[i]*3.14;
}
return res;
}