I would like to encapsulate different algorithms as strategies. All strategies would provide a single method potentially differing in the number and types of parameters.
template <typename... Arguments>
double price(Arguments... parameters)
The strategies should not be coded directly in the class using them. Is there a simple way of implementing the strategy design pattern using variadic templates? I'm also aware of "policy-based design" and I m trying to achieve something similar using variadic templates
Do you mean, you want to have strategies that require different arguments, that can be transparently forwarded by the user of the strategy, without it knowing about any of the actual parameters?
Demo (contrived but illustrative, I hope). See it live on http://ideone.com/MExyx
#include <string>
#include <iostream>
struct StratA {
enum gender { male, female, unknown };
double price(std::string name, int age, gender g) const
{ return 42; }
};
struct StratB {
double price(int age, int volume, double historic_rate) const
{ return (age*age*historic_rate)/volume; }
};
template <typename PricingStrategy=StratA>
struct SomeEngine
{
template <typename... Args>
void doSomethingInvolvingPricing(std::string logmessage,
Args... args) // involving pricing
{
std::cout << logmessage << ": " << PricingStrategy().price(std::forward<Args>(args)...) << '\n';
}
};
int main()
{
SomeEngine<>().doSomethingInvolvingPricing("default", "name", 18, StratA::female);
SomeEngine<StratB>().doSomethingInvolvingPricing("overridden", 18, 3000, 4.5);
}
Output (also on ideone):
default: 42
overridden: 0.486