0

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.

closed as off-topic by gnat, 8bittree, Bart van Ingen Schenau, amon, BobDalgleish Oct 18 '17 at 21:37

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – gnat, 8bittree, Bart van Ingen Schenau
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
4

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.