我知道函数调用中存在歧义.有没有办法调用foo()函数

I understood that there is an ambiguity in a function call . Is there a way to call foo() function?

本文关键字:foo 调用 函数 函数调用 存在 歧义 有没有 我知道      更新时间:2023-10-16
#include< iostream >
using namespace::std;
int foo();              //function with no argument
int foo(int=10);        //Default argument
int foo()
{
cout<<"n Foo , I am foo n";
return 0;
}
int foo(int f)
{
cout<<"n I am Foo too.n";
return 0;
}
int main()
{
foo();
foo(2);
cin.get();
return 0;
}

没有干净的方法,只有丑陋的方法。例如:

static_cast<int (*)()>(&foo)();

或者:

int (*p)() = &foo;
(*p)();

最重要的是,由于模糊性,您不能依赖过载解决方案。因此,您需要使用这种方法明确地解析符号。

首选的解决方案是首先避免出现不明确的过载。通常可以找到一些合理的方法来做到这一点,但方式取决于实际细节。

您可以显式强制转换函数指针,但不确定是否应该强制转换。

#include <iostream>
using namespace::std;
int foo();              //function with no argument
int foo(int=10);        //Default argument
int foo()
{
cout<<"n Foo , I am foo n";
return 0;
}
int foo(int f)
{
cout<<"n I am Foo too.n";
return 0;
}
int main()
{
static_cast<int(*)()>(foo)();
foo(2);
cin.get();
return 0;
}

编辑:

这一行static_cast<int(*)()>(foo)();只是对函数的强制转换和调用的缩写形式。

为了解释它,我们可以通过三个步骤将其拆开:

将myFuncType定义为指向返回int且不接受参数的函数的指针

using myFuncType = int(*)();

通过将重载名称foo强制转换为不带参数的函数类型来解决该名称,并将其存储在名为f 的变量中

auto f = static_cast<myFuncType>(foo);
// or auto f = (myFuncType)foo;
// or auto f = (myFuncType)&foo; C++ actually does the address-of implicitly with functions

最后一个是调用函数指针

f(); //or (*f)(); C++ automatically dereferences function pointer on call, but you can also manually dereference
  1. 删除默认参数,或者
  2. 重命名其中一个函数

不清楚为什么这两个函数声明使用相同的名称。只有当他们应该"做同样的事情"时,你才应该这么做。

删除默认参数

如果这两个函数应该做相同的事情,那么:

当你为一个函数指定一个默认参数时,你会得到一个额外的函数签名

int foo(int arg=10);

还可以给你

int foo();

它说,对于*对foo()的任何调用">",arg的值都是10

但是,您已经加入了一个额外的int foo();,它返回0,这让编译器感到困惑。在更抽象的层面上,您实际上混淆了自己关于函数应该做的"事情"的默认参数是什么。

重命名其中一个函数

如果这两个函数不做相同的事情,它们就不应该有相同的名称。有几种不同的方法可以做到这一点:

  • 为一个新名字
  • 将其中一个放在命名空间中
  • 使用模板