代码之家  ›  专栏  ›  技术社区  ›  user9590073

函数能否返回多个不同类型的值?

  •  3
  • user9590073  · 技术社区  · 8 年前

    它认为返回多个值(使用不同的类型)会很有趣来自C++函数调用。

    因此,我四处寻找可能找到一些示例代码,但不幸的是,我找不到与此主题匹配的任何内容。

    我想要一个像。。。

    int myCoolFunction(int myParam1) {
        return 93923;
    }
    

    使用不同的类型返回多种不同类型的值,如

    ?whatever? myCoolFunction(int myParam1) {
        return { 5, "nice weather", 5.5, myCoolMat }
    }
    

    那么使用C是否可以实现类似的功能++ (我的想法是使用一个特殊的AnyType向量,但我找不到示例代码) 还是我必须继续打这类电话? (见下文)

    void myCoolFunction(cv::Mat &myMat, string &str){
       // change myMat
       // change str
    }
    

    笔记 :因此每次返回的元素的顺序和计数都将相同->设置保持不变(如 1.:double, 2.:int 在任何情况下)

    5 回复  |  直到 8 年前
        1
  •  4
  •   Holt 111111    8 年前

    如果要返回多个值,可以返回包含不同值的类的实例。

    如果您不在乎失去语义,可以返回 std::tuple 1. :

    auto myCoolFunction(int myParam1) {
        return std::make_tuple(5, "nice weather", 5.5, myCoolMat);        
    }
    

    如果要强制类型(例如 std::string 而不是 const char * ):

    std::tuple<int, std::string, double, cv::Mat> myCoolFunction(int myParam1) {
        return {5, "nice weather", 5.5, myCoolMat};
    }
    

    在这两种情况下,您都可以使用 std::get :

    auto tup = myCoolFunction(3);
    std::get<0>(tup); // return the first value
    std::get<1>(tup); // return "nice weather"
    

    1. 如果您有兼容C++17的编译器,则可以使用 template argument deduction 然后简单地返回 std::tuple{5, "nice weather", 5.5, myCoolMat}

        2
  •  3
  •   einpoklum    7 年前

    是的,函数可以在 std::tuple ,从C++11开始在标准库中提供:

    #include <tuple>
    
    std::tuple<int, std::string, double, cv::Mat>
    myCoolFunction(int myParam1) {
        return { 5, "nice weather", 5.5, myCoolMat }
    }
    

    如果允许使用C++14代码,您甚至不必声明类型:

    #include <tuple>
    
    auto myCoolFunction(int myParam1) {
         return std::make_tuple(5, "nice weather", 5.5, myCoolMat);
    }
    

    here is proof both of these versions compile (无 cv::Mat -我认为GodBolt没有这一点)。

    备注:

    • 如果您使用 std::make_tuple ,类型可能与您期望的不完全相同。例如,在这种情况下,您将得到 char * 虽然在显式定义元组时,可以强制它 std::string 就像我上面所说的。这通常不是问题。
    • 如果某些数据很大,您可以尝试 std::move it,以避免复制整个内容,例如通过 std::move(myCoolMat)
        3
  •  2
  •   Abhishek Keshri    8 年前

    可以返回结构或使用std::tuple。

    使用struct,您可以执行以下操作:

    myStruct create_a_struct() {
      return {20, std::string("baz"), 1.2f};
    }
    

    和std::tuple

    std::tuple<int, std::string, float> create_a_tuple() {
      return {20, std::string("baz"), 1.2f};
    }
    
        4
  •  0
  •   Bathsheba    8 年前

    (真的是为了好玩,为了展示C++的强大功能,而不是其他任何东西。)

    一种方法是使用

    std::shared_ptr<void>

    作为返回类型。这是允许的,因为 std::shared_ptr 支架 类型消除 (不幸的是, std::unique_ptr 所以你必须排除这种可能性。)

    显然,在函数中,您需要使用 std::make_shared 或类似。

    参考号: Why is shared_ptr<void> legal, while unique_ptr<void> is ill-formed?

        5
  •  -4
  •   manglano    8 年前

    返回std::variant的std::vector,其中std::variant被模板参数化为您选择的类型。如果任何类型实际上都是可能的,我不知道为什么要用结构而不是简单地写入内存空间;没有结构中对象和类型的确定性概念的价值很低。

    推荐文章