It's been a while that I've been doing C++ but I'm not familiar with templates.
Recently, I tried to write a class that wrap a std::vector<std::tuple<Types...>>
. This class must have member functions, and I really need to be able to iterate over the tuple. In fact, if I am able to print every element of a tuple (in the order), I would be able to do everything I need.
I found a solution using a cast, but I'm not really confident with it since it is based on a cast that I don't really like (plus, when I try to use static_cast
, it doesn't compile anymore).
My question is, is the following code correct, portable, is it a hack and should I find another way to do this than to use this cast ? Also, this cast is probably a runtime-cast right ? Is there a way to do what I want without this ?
std::ostream& operator<<(std::ostream& out, std::tuple<> const& tuple)
{
return out; // Nothing to do here
}
template<typename First, typename... Types>
std::ostream& operator<<(std::ostream& out, std::tuple<First, Types...> const& tuple)
{
out << std::get<0>(tuple) << " ";
// The cast that I don't like
return out << (std::tuple<Types...>&) tuple;
}
int main()
{
auto tuple = std::make_tuple(1, 2.3, "Hello");
std::cout << tuple << std::endl;
return 0;
}
Thank you in advance for your answers.