I have a class, let's call it Sample
with variadic template arguments. This class contains a function run(Args... args)
. This class also implements a stream operator that calls this function.
The class looks like this:
template<typename ...Args>
class Sample
{
void run(Args... args)
{
// do something
}
Sample& operator<<(const tuple<Args...>& args)
{
run(unpack_somehow(args)...);
return *this;
}
};
Now I want to use the stream operator to concat multiple calls, by passing the arguments via the brace initialization of tuples:
void main()
{
Sample<int, string, int> s;
// doesn't work :(
s << {1, "msg", 2} << {1, "msg", 2};
}
I know I could just write make_tuple(1, "msg", 2)
and it would work, but I'm looking for a solution that doesn't need additional function calls like make_tuple
.
Is there a way to implement such a feature that I can pass the arguments in braces (or maybe by comma separation by overloading the comma operator)?
When you use the line s << {1, "msg", 2} << {1, "msg", 2};
it does not provide the C++ compiler with enough information to deduce what you mean by those initializer lists.
Unless you give a hint to compiler (use a make_tuple
or pass an actual tuple
variable) it won't know what you mean and won't be able to call the appropriate operator<<()
.
Looks like you are out of luck. This cannot be done in the way your question is posted.