Reputation: 55
In c++11 I have functions
double f(double x1);
double f(double x1, double x2);
double f(double x1, double x2, double x3);
double h(double x);
I also have functions
double g(std::vector<double> y, double x1);
double g(std::vector<double> y, double x1, double x2);
double g(std::vector<double> y, double x1, double x2, double x3);
The implementation of g is something like
double g(std::vector<double> y, double x1, double x2, double x3)
{
double ans = 0.0;
for(g : y)
{
ans = h(g) * f(x1, x2, x3);
}
return ans;
}
Is there an elegant (templated) way of doing this instead of writing g 3 times with overloaded arguments?
Upvotes: 2
Views: 137
Reputation: 275878
template<typename... Ts>
double g(std::vector<double> v, Ts&&...ts ) {
double ret = 1;
for(auto x:v){
ret *= h(x)*f(ts...);
}
return ret;
}
if you want to restrict the ts
to be double
s beyond calling f
, it needs more work. Otherwise, the above is enough.
(Note the resriction work gets prettier in C++1y with concepts lite: in C++11 I vote to skip the restriction of Ts
to double
s, and just rely on f
only taking double
s.)
Upvotes: 10