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) {
        return std::make_tuple("Hello", 1, 4.2);
        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.

  • As far as I know when you call get you will need to fix the template parameters so both returns will need to return the same type. After all what type will you declare a variable which will store the result of get? – apokryfos Oct 4 '17 at 13:12
  • You need sum types, which C++ lacks. – gardenhead Oct 6 '17 at 1:11

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.