简体   繁体   English

如何在执行期间终止(或返回)具有结构类型的自动功能?

[英]How do I terminate (or return from) an auto function with a structure type during execution?

How do I terminate an "auto" type function with a structure return type during execution? 如何在执行期间终止具有结构返回类型的“自动”类型函数?

I want to escape the auto function 'Func' (not the entire program) when some condition is satisfied as follows: 我想在满足某些条件时转义自动函数'Func'(不是整个程序),如下所示:

#include "stdafx.h"
#include <vector>
#include <tchar.h>
#include <iostream>

using namespace std;

auto Func(int B, vector<int> A) {
    for (int a = 0; a < B; a++)
    {
        A.push_back(a);
        if (a == 2)
        {
            cout << " Terminate Func! " << endl;
            // return; I want to terminate 'Func' at this point  
        }
    }

    struct result { vector <int> A; int B; };
    return result{ A, B };
}

int _tmain(int argc, _TCHAR* argv[])
{

    vector<int> A;
    int B = 5;

    auto result = Func(B, A);
    A = result.A;
    B = result.B;

    for (int a = 0; a < A.size(); a++)
    {
        cout << A[a] << endl;
    }
}

I don't want to use "exit()" because I just want to terminate a function not the program. 我不想使用“exit()”因为我只想终止一个函数而不是程序。

You can return a define the return type result at the top of the function and then return an "empty" instance like this: 您可以在函数顶部返回一个定义返回类型的result ,然后返回一个“空”实例,如下所示:

auto Func(int B, vector<int> A) {
    struct result { vector <int> A; int B; };

    for (int a = 0; a < B; a++)
    {
        A.push_back(a);
        if (a == 2)
        {
            return result{{}, 0};
        }
    }

    return result{ A, B };
}

If you don't want a valid object to be returned when the early-return condition is met, consider returning a std::optional<result> from the function, and specifically std::nullopt in the early return branch. 如果您不希望在满足早期返回条件时返回有效对象,请考虑从函数返回std::optional<result> ,特别是在早期返回分支中返回std::nullopt But this requires C++17. 但这需要C ++ 17。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM