Pass a heterogeneous initializer list to a stream operator

184 Views Asked by At

Is it possible to pass to a debug streaming operator a list of heterogeneous types that are streamable?

string str("blabla");
std::cout << {"A", 3,  str} << std::endl;

I guess it could be possible with something like a variadic template? I want the operator << to call each of the elements in the list and append a comma.

1

There are 1 best solutions below

5
On

You can't use initializer list for heterogeneous types, but std::tuple is ok.

Make sure there is no unnecessary copy made. Here is a solution using C++17.

#include <tuple>
#include <string>
#include <iostream>

template<class... Ts>
std::ostream&
operator<<(std::ostream &os, std::tuple<Ts...> &&tp)
{
    auto lam = [&] (auto &&arg0, auto&& ...args) -> auto&& {
        os << arg0;
        ([&] (auto&& arg) {
            os << ", " << arg;
        } (args), ...);
        return os;
    };

    return std::apply(lam, std::move(tp));
}

int main() {
    std::string str("blabla");
    std::cout << std::forward_as_tuple("A", 3,  str) << std::endl;
}