Evgenii Legotckoi
Aug. 21, 2019, 1:56 p.m.

C++14 - unnamed structure as auto value returned by function

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

  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. // Declare a function that will return auto
  7. auto getHero()
  8. {
  9. // We will form an unnamed structure of the return value
  10. struct
  11. {
  12. std::string name;
  13. std::string surname;
  14. int age;
  15. } result { "James", "Bond", 42 }; // Initially initialize the structure object
  16. return result; // Then you can return the resulting structure, the compiler will do everything thanks to auto
  17. }
  18.  
  19. int main()
  20. {
  21. // We return this value immediately to the auto variable
  22. auto hero = getHero();
  23. // And we can already use this object, while it will have named fields
  24. std::cout << hero.surname << "..." << hero.name << " " << hero.surname << " " << hero.age << std::endl;
  25. return 0;
  26. }
  27.  

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.

  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. // Declare a lamda function that will return auto
  9. auto getHero = []()
  10. {
  11. // We will form an unnamed structure of the return value
  12. struct
  13. {
  14. std::string name;
  15. std::string surname;
  16. int age;
  17. } result { "James", "Bond", 42 }; // Initially initialize the structure object
  18. return result; // Then you can return the resulting structure, the compiler will do everything thanks to auto
  19. };
  20.  
  21. // We return this value immediately to the auto variable
  22. auto hero = getHero();
  23. // And we can already use this object, while it will have named fields
  24. std::cout << hero.surname << "..." << hero.name << " " << hero.surname << " " << hero.age << std::endl;
  25. return 0;
  26. }
  27.  

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html