C++ 一个函数,可以根据接受的值返回两种类型之一

C++ A function that can return one of two types depending on the accepted value

本文关键字:两种 类型 返回 一个 函数 C++      更新时间:2023-10-16
fun(int a) {
if (a) return a; return "empty";
}

我需要一个获取数字的函数,并根据它的数字返回 int 变量或字符串。 请告诉我如何实现这样的功能。

对于 C++ 17,您可以使用变体:

std::variant<int, std::string> fun(int a) {
if (a) return a; return "empty";
}

或者使用具有可选功能的结构:

struct r {
std::optional<int> i;
std::optional<std::string> s;
};
r fun(int a) {
r out;
if (a) out.i = a; else out.s = "empty";
return out;
}

或者对于先前的标准,请使用带有指示有效性的字段的结构。

struct r {
enum class type {i, s};
int i;
std::string s;
type t;
};
r fun(int a) {
r out;
if (a) {
out.i = a;
out.t = r::type::i;
else {
out.s = "empty";
out.t = r::type::s;
}
return out;
}

像python这样的可解释语言对参数类型和返回值的类型没有限制。但是,C++只能接受和返回预定义类型的值。 现在,除了其他答案之外,如果您没有 C++17,您可以尝试以下方式:

std::pair<int, string> func(int a)
{
if(a) return std::make_pair(a , "");
return std::make_pair(0,"string");    
}

在被调用方中,您可以针对 std::p air 的两个成员检查非空。

您可以在例外的情况下完成此流程!例如,如果func希望使用大于 5 的数字,则可以执行以下操作:

int func(int a) {
if (a > 5) { return a; }
throw std::runtime_error("Empty");
}
int main() {
try {
int x = func(3);
// Do some stuff with x...
} catch(const std::exception &e) {
std::cout << "Looks like the num is " << e.what();
}
}

因此,如果事情进展顺利,您要么处理int,要么,如果发生了不好的事情,您可以从异常中获取字符串并处理它。

您可以通过将两个不同的任务拆分为单独的函数并从那里继续执行来实现此目的。

#include <iostream>
using namespace std;int inputValue = 0;
int returnInt() {
std::cout << "Returning your int" << std::endl;
return inputValue;
}
string returnString() {
std::cout << "Returning your string" << std::endl;
return "Your string";
}
int main() {
std::cout << "Please type in a number" << "t";
std::cin >> inputValue;
if (inputValue > 5) {
returnInt();
}
else {
returnString();
}
}