简体   繁体   English

如何在不使用 c++ 中的“return”的情况下使用返回值退出 function

[英]How to exit a function with a return value without using "return" in c++

How would I exit a function with a return value without using return .我如何在不使用return的情况下退出带有返回值的 function 。

Is there something like this in c++: c++中是否有这样的东西:

auto random_function() {
    printf("Random string"); // Gets executed

    exit_with_return_value(/* Any random value. */);

    printf("Same string as before"); // Doesn't get executed
}

Because I'm aware about exit() which takes a exit code.因为我知道exit()需要退出代码。 But is there any way I could exit with a return value.但是有什么方法可以退出并返回值。

It is just that I can't call return is parentheses like this:只是我不能调用return是这样的括号:

( return /* random value*/ );

But I can call functions in parentheses,但我可以在括号中调用函数,

(exit(0));

My use case:我的用例:

 template <typename ...Parameters>
 class Parameter_Pack 
 {
 private:
     void* paramsAddr[sizeof...(Parameters)];

 public:
     Parameter_Pack(Parameters ...parameters) { 
        size_t count = 0;
       
       ((
        parameters, 
        this->paramsAddr[count] = malloc(sizeof(Parameters)), 
        *(Parameters*)paramsAddr[count] = parameters, 
        count++
      ), ...);
    }

    auto operator[](size_t index) {
        size_t count = 0;
        try {
           (((count == index ? : return * 
             (Parameters*)paramsAddr[index] : * 
             (Parameters*)paramsAddr[index]), count++), ...);
         } catch (Parameters...) {
              std::cout << "Error: " << std::endl;
         }
   }

    const size_t size() const {
        return sizeof...(Parameters);
    }
};

The problem is I can't return in auto operator[](size_t index) .问题是我无法返回auto operator[](size_t index)

The compiler error is:编译器错误是:

"expected primary-expression before 'return'" “'return'之前的预期主要表达式”

This doesn't answer your question directly, but instead of reinventing the wheel why not unpack the parameter pack into an std::tuple .这并不能直接回答您的问题,但与其重新发明轮子,不如将参数包解压缩到std::tuple中。 You can then use std::get to access the object 's by index.然后,您可以使用std::get按索引访问object

#include <iostream>
#include <tuple>

template<typename ...Args>
static void unpack(Args&& ...args) 
{
    std::tuple pack{ std::forward<Args>(args)... };

    int first = std::get<0>(pack);
    std::cout << first << '\n';

    const std::string& second = std::get<1>(pack);
    std::cout << second << '\n';

    bool third = std::get<2>(pack);
    std::cout << std::boolalpha << third << '\n';
}

int main()
{
    unpack(42, std::string{ "Some string" }, false);
}

OK, so the only thing I could come up with that kind of does what you want is to use a std::vector in conjunction with a std::variant .好的,所以我唯一能想到的就是将std::vectorstd::variant结合使用。

Personally I think this would be an annoying API to use but it will allow you to return multiple types from the subscript operator and doesn't require a constant expression, ie index can be a runtime value.我个人认为这将是一个恼人的 API 使用,但它将允许您从下标operator返回多种类型并且不需要常量表达式,即index可以是运行时值。

#include <iostream>
#include <variant>
#include <vector>
#include <string>

template<typename ...Args>
class Pack {    
public:
    using Types = std::variant<Args...>;

    Pack(Args... args)
        : pack_{ std::move(args)... }
    {}

    Types& operator[](const std::size_t index) {
        return pack_.at(index);
    }

    std::size_t size() const noexcept {
        return pack_.size();
    }

private:
    std::vector<Types> pack_;
};

int main() {
    Pack pack{42, std::string{ "Some string" }, false};
    std::cout << pack.size() << '\n';

    if (int* num = std::get_if<int>(&pack[0])) {
        std::cout << "My num: " << *num << '\n';
    }
}

return is a statement. return是一个声明。 Statements can't be part of a larger expression, so you can't return as a subexpression of some larger expression.语句不能是较大表达式的一部分,因此您不能作为某个较大表达式的子表达式return

throw is an expression. throw是一个表达式。 It can be a subexpression of a larger expression, and you can throw any object you like.它可以是更大表达式的子表达式,你可以throw任何你喜欢的 object。

It will be inconvenient for your callers, particularly if you mix it with an ordinary return.这会给您的来电者带来不便,特别是如果您将其与普通回报混合使用。 It will also not match the expectations other programmers have for how functions work.它也不符合其他程序员对函数工作方式的期望。 For that reason, I suggest you don't throw when you mean return .出于这个原因,我建议你不要throw当你的意思是return

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

相关问题 如何在不使用C ++ / C的阻塞函数的情况下将值从线程返回到主函数 - How to return value from the thread back to main function without using blocking function in C++/C 如何在不退出 function 并随后将其存储在 c++ 的情况下返回一个值 - how to return a value without exiting a function and storing it subsequently, in c++ 没有返回语句的C ++返回值 - C++ return value without return statement C++ 函数的返回值 - C++ return value of a function 在C ++中将一个函数的返回值用作另一个函数的参数 - using the return value of one function as an argument in another function in c++ C ++在技术上如何在没有副本的情况下移动函数返回值? - C++ how is it technically possible to move a function return value without a copy? C++ pthread - 如何在不等待完成的情况下从线程 function 返回值? - C++ pthread - how to return a value from thread function without waiting for finish? 如何在C ++中从函数获取返回值而不将值赋给变量 - How to get a return value from a function without assigning values to its variables in c++ Function 不返回值,而在 c++ 中使用向量 - Function does not return a value, while using a vector in c++ C ++数学比较使用函数返回值不起作用 - C++ mathematical comparison using function return value not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM