Evgenii Legotckoi
Evgenii LegotckoiAug. 21, 2019, 3:56 a.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

#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;
}

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
m
moogoNov. 22, 2024, 3:17 p.m.
Mosquito Spray System Effective Mosquito Systems for Backyard | Eco-Friendly Misting Control Device & Repellent Spray - Moogo ; Upgrade your backyard with our mosquito-repellent device! Our misters conce…
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 10:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 10:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks