如何指示某些过载功能

How to indicate certain overloaded function?

本文关键字:功能 何指示 指示      更新时间:2023-10-16

例如,我们有一些C 代码,其中一些函数用某些参数执行另一个函数。

#include <iostream>
using namespace std;
template <typename T, typename F>
void todo(const T& param, const F& function)
{
  function(param);
}
void foo(int a)
{
  cout << a << endl;
}
int main()
{
  int iA = 1051;
  todo(iA, foo);
  return 0;
}

但是,如果我们添加了一个名称foo

的功能
void foo(double a)
{
  cout << a << endl;
}

然后编译器不知道哪个函数生成模板。

!!!重要!!!

这不是真实的代码,这就是示例。在通过重新加载函数作为参数中的问题。

有人知道如何明确指示某些功能吗?

todo(iA, static_cast<void (*)(int)>(&foo));

是一种方式,以呼叫网站的可读性为代价。

测试代码(保留您的2个字符凹痕 - 我是Myrmidon):

#include <iostream>
using namespace std;
template <typename T, typename F>
void todo(const T& param, const F& function)
{
  function(param);
}
void foo(double a)
{
  cout << "double " << a << endl;
}
void foo(int a)
{
  cout << "int " << a << endl;
}
int main()
{
  int iA = 1051;
  todo(iA, static_cast<void (*)(int)>(&foo));
  todo(iA, static_cast<void (*)(double)>(&foo));
  return 0;
}

输出:

int 1051
double 1051

请参阅https://www.ideone.com/deilbe

auto identifier = type{value}

这是Sutter Mill在其AAA中建议的语法(几乎总是是自动),当时是第94周的GURU,当时需要进行特定类型。

它在这里完全适用:

int iA = 1051;
using foo_int_type = void(*)(int);
auto non_ambiguous_int_foo = foo_int_type{foo};
todo(iA, non_ambiguous_int_foo);

coliru上的现场演示

您可以使用static_cast选择正确的功能超载。例如:todo(iA, static_cast<void(&)(double)>(foo))