Let's look at an interesting construction from the C++14 standard, which allows you to return the structure used in one place of the code, but you need to return an object with named fields.
Such a construction can serve as a replacement for std::tuple. At the same time, we will not need to declare any additional structures that we are not going to transfer anywhere, since we need to get only a set of data that we will somehow use immediately at the place of return and will not transfer further in the same form.
Normal function example
- #include <iostream>
- #include <string>
- using namespace std;
- // Declare a function that will return auto
- auto getHero()
- {
- // We will form an unnamed structure of the return value
- struct
- {
- std::string name;
- std::string surname;
- int age;
- } result { "James", "Bond", 42 }; // Initially initialize the structure object
- return result; // Then you can return the resulting structure, the compiler will do everything thanks to auto
- }
- int main()
- {
- // We return this value immediately to the auto variable
- auto hero = getHero();
- // And we can already use this object, while it will have named fields
- std::cout << hero.surname << "..." << hero.name << " " << hero.surname << " " << hero.age << std::endl;
- return 0;
- }
Lambda function example
The example with the lambda function will not differ much in this case from the usual function, there will simply be a different place for the declaration.
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- // Declare a lamda function that will return auto
- auto getHero = []()
- {
- // We will form an unnamed structure of the return value
- struct
- {
- std::string name;
- std::string surname;
- int age;
- } result { "James", "Bond", 42 }; // Initially initialize the structure object
- return result; // Then you can return the resulting structure, the compiler will do everything thanks to auto
- };
- // We return this value immediately to the auto variable
- auto hero = getHero();
- // And we can already use this object, while it will have named fields
- std::cout << hero.surname << "..." << hero.name << " " << hero.surname << " " << hero.age << std::endl;
- return 0;
- }