0

In newer versions of the C++ standard, we are allowed to write functions that have multiple return values such as

std::tuple<int, std::string, float> someFunction0();

This forces us to call the functions as

int a;
std::string last_name;
float f_par;
std::tie(a, last_name, f_par) = someFunction0();

My question is, is there something that prevents the C++ committee from introducing a "simpler" form of multiple return value syntax? Such as

[int, std::string, float] someFunction1();

which would allow you to declare more inline when calling the function

[int a, std::string last_name, float f_par] = someFunction1();

(There are probably better syntactic solutions than the one that I provided.)

Compiler-wise, it shouldn't be an issue, right?

  • 6
    If I understand you correctly, I think what you are asking about [already exists](https://en.cppreference.com/w/cpp/language/structured_binding). – François Andrieux Oct 07 '19 at 15:38
  • 4
    Possible duplicate of [Structured binding to replace std::tie abuse](https://stackoverflow.com/questions/40241335/structured-binding-to-replace-stdtie-abuse). – François Andrieux Oct 07 '19 at 15:41
  • Ah, rats, seems like I haven't done my homework! Thanks for the answers! – user2372772 Oct 07 '19 at 15:52
  • 3
    Rare is the circumstance where you need a function to return multiple values, but that the collection of those values is not sufficiently meaningful in and of itself to be worthy of having a named struct type. And even if the group of return values is inherently meaningless, using a struct means that you can at least give the return values *names*, which makes it clear on the receiving end what the values *mean*. Think of how terrible `map::insert` code is because of the inscrutable meaning of `pair.second`. – Nicol Bolas Oct 07 '19 at 15:56

1 Answers1

3

In your example std::tuple<int, std::string, float> someFunction0(); still returns one tuple object, comprised of multiple sub-objects.

is there something that prevents the C++ committee from introducing a "simpler" form of multiple return value syntax?

You can use C++17 structured binding declaration to unpack/destructure it:

Case 2: binding a tuple-like type

float x{};
char  y{};
int   z{};

std::tuple<float&,char&&,int> tpl(x,std::move(y),z);
const auto& [a,b,c] = tpl;
// a names a structured binding that refers to x; decltype(a) is float&
// b names a structured binding that refers to y; decltype(b) is char&&
// c names a structured binding that refers to the 3rd element of tpl; decltype(c) is co`
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271