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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.