我可以让一个函数返回多个类型吗?

Can i make a function return more than one type?

本文关键字:返回 类型 函数 一个 我可以      更新时间:2023-10-16

如何使一个函数返回多个类型?我想使一个函数称为视图,返回视图名称,ID和工资我可以让一个单一的(get)函数做到这一点吗?

可以返回一个struct或者一个std::tuple

类似:

struct foo
{
    std::string Name;
    unsingned int ID;
    unsigned int salary;
};
foo bar()
{
    return {"Smith", 42, 1000};
}

您可以使用标准类std::tuple。例如

#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string, int, float> f()
{
    return std::make_tuple( "Doxim", 1, 3500.00 );
}
int main()
{
    auto t = f();
    std::cout << std::get<0>( t ) << 't'
              << std::get<1>( t ) << 't'
              << std::get<2>( t ) << std::endl;
    return 0;
}

输出为

Doxim   1   3500

#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string, int, float> f()
{
    return std::make_tuple( "Doxim", 1, 3500.00 );
}
enum { NAME, ID, SALARY };
int main()
{
    auto t = f();
    std::cout << std::get<NAME>( t ) << 't'
              << std::get<ID>( t ) << 't'
              << std::get<SALARY>( t ) << std::endl;
    return 0;
}

你可以让一个函数返回一个包含这些属性的结构。

struct Foo
{
 int value1;
 int value2;
};
Foo SomeFunction()
{
Foo f = { 1, 2 };
return f;
}

您有两个选择:

要么使用in-out参数,要么创建一个包含所有类型的结构/类