如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数

How to create two functions with the same name and different return type and runned based on boolean parameter

本文关键字:返回类型 于布尔 函数 运行 参数 何创建 创建 两个      更新时间:2023-10-16

我有两个名称相同但返回类型的函数。我想根据他们的第三个参数运行函数。如果第三个参数为真,我想运行第一个参数,如果参数为假,则运行第二个函数。我自己尝试不同的东西,因为我在网上找不到信息,我不确定这怎么称呼。这是我尝试做的:

static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);

如果有人能解释如何做到这一点,或者至少给我一个指向一些信息的链接,我将不胜感激。

此解决方案不是关于拥有两个不同的函数,而是如果您希望函数使用 boost::any 根据布尔值返回不同的类型。

boost::any function(int a, int b, const bool c) {
std::string str = "Hello world!";
int num = 10;
if ( c ) {
return boost::any(num);
} else {
return boost::any(str);
}
} 

这将使用函数中的第三个参数来决定您应该执行哪个返回。 根据函数的大小,这可能是一个更糟糕的解决方案,但如果你真的想使用布尔值作为参数,我相信这应该有效。

文档:速推

与此答案相关的问题:返回未知类型的函数

您可以创建函数模板并为不同的返回类型添加专用化。然后,您可以使用bool参数作为模板参数:

template<bool>
auto function(int, int);
template<>
auto function<true>(int a, int b)
{
// ...
return int{};
}
template<>
auto function<false>(int a, int b)
{
// ...
return std::string{};
}

然后,将像这样调用这些函数:

int a = function<true>(1,2);
std::string b = function<false>(1,2);

这是一个演示。

请注意,bool参数必须在编译时知道,并且不能是运行时参数。

虽然这种技术可以工作,但请注意,这会让很多 c++ 程序员感到困惑。它们通常期望函数始终返回特定类型。

与您的问题更相关;这实际上不会使代码更具可读性。相反,具有单独的命名函数可能是一种更具可读性的方法:

int int_function(int a, int b);
std::string str_function(int a, int b);

可以这样称呼:

int a = int_function(1,2);
std::string b = str_function(1,2);