Search code examples
c++templatesvariadic-templates

The need to pass different types in the initialization_list


I'm looking for a template based way to pass arbitrary number of params in the initialization_list(s).

Something like:

func({0, 1}, {0, 2.0f}, {0, "boo"}, ...);

or

func({{0, 1}, {0, 2.0f}, {0, "boo", ...}});

In the same time I want to be able to check the type of the second param in each (inner) brace. Maybe get sizeof(T) maybe do some if constexpr(std::is_same<T, ...>::value) match.

Is it possible? If so how would func() definition look like?


Solution

  • Make f take std::initializer_list<std::pair<std::any, std::any> >:

    void f(std::initializer_list<std::pair<std::any, std::any> > il) {
        for (auto it = il.begin(); it != il.end(); ++it) {
            const std::type_info& type1 = it->first.type();
            const std::type_info& type2 = it->second.type();
            if (type1 == typeid(int)) {
                int val1 = std::any_cast<int>(it->first);
            }
            // ...
        }
    }
    

    If you have only a couple possible types, you can use std::variant<int, float, /*e.g.; etc. */> instead of std::any.