Function returning different tuples [closed]
https://softwareengineering.stackexchange.com/questions/358563
Question
I am trying to learn C++11/14 new features and I am playing with tuple
and variadic. I wonder if it is possible to use tuples to return multiple values that are not fixed at compile time.
Something like (not working code):
template <typename... Ts>
std::tuple<Ts...> get(bool f) {
if(f)
return std::make_tuple("Hello", 1, 4.2);
else
return std::make_tuple(3.3, 'i');
}
I also read about auto
return deduction, but it can be used only when all return
have the same type.
Solution
The short answer is that no it is not. The compiler can do some type deduction to figure out the return type without your specifying it explicitly (at least in some cases), but in every case the type itself must be fixed at compile time.
In theory, you could (for example) return something like an std::vector<boost::any>
to allow returning an arbitrary number of arbitrary types. I'd caution, however, that this is likely to be more of a problem than a solution. To be useful, you nearly always want to place tighter constraints than that.