C++ Chain of Responsbility
#include <iostream>
#include <vector>
#include <functional>
struct Condiment
{
std::function<std::string()> description;
std::function<float()> price;
};
class Sugar
{
public:
static std::string description() { return "-Sugar-"; }
static float price() { return 0.07f; }
};
class Milk
{
public:
static std::string description() { return "-Milk-"; }
static float price() { return 0.13f; }
};
template<typename Call, typename NextCall>
static auto accu(Call call, NextCall next) -> decltype(call() + next())
{
if(next) return call() + next();
return call();
}
int main()
{
Condiment condiments;
condiments.description = [=] { return accu(&Milk::description, condiments.description); };
condiments.description = [=] { return accu(&Sugar::description, condiments.description); };
condiments.description = [=] { return accu(&Sugar::description, condiments.description); };
condiments.price = [=] { return accu(&Milk::price, condiments.price); };
condiments.price = [=] { return accu(&Sugar::price, condiments.price); };
condiments.price = [=] { return accu(&Sugar::price, condiments.price); };
std::cout << "Condiments: " << condiments.description() << '\n';
std::cout << "Price: " << condiments.price() << '\n';
return 0;
}