C++: match arbitrary length of argument with arbitrary length template

Viewed 49

I'm learning template, and have this program:

#include <iostream>

class Beef {};

class Chicken {};

template<class Raw>
class Ingredient {};

template<class Raw>
class Menu {
public:
    void cook(const Ingredient<Raw> ingredient) {
        std::cout<<"cooking\n";
    }
};

int main() {
    auto beef = Ingredient<Beef>();
    auto chicken = Ingredient<Chicken>();

    auto menu = Menu<Chicken>();
    menu.cook(chicken);
    return 0;
}

This program works well so far when Meun is given only 1 template parameter and function cook takes also 1 parameter. Then I got stuck when extend Menu to accept more than 1 template parameter:

template<class... Raw>
class Menu {
public:
    void cook() {
        std::cout<<"cooking\n";
    }
};

How do I extend cook accordingly to accept arbitrary length of argument and also automatically type check during compile time? Ideally I hope to use the APIs in such a way:

    auto beef = Ingredient<Beef>();
    auto chicken = Ingredient<Chicken>();
    auto lamb = Ingredient<Lamb>();

    auto menu = Menu<Chicken, Beef>();
    menu.cook(chicken, beef);                    // compile
    menu.cook(beef, chicken);                    // also compile
    menu.cook(beef);                             // error
    menu.cook(beef, chicken, lamb);              // error

How should I implement cook()?

0 Answers
Related