为什么decltype无法使用重载函数?

cf *_*ica 13 c++ overloading decltype c++11

decltype 如果您正在调用它的函数被重载,则会失败,如下面的代码所示:

#include <iostream>

int test(double x, double y);
double test(int x, int y);
char test(char x, int y);

int main()
{
  std::cout << decltype(test) << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

error: decltype cannot resolve address of overloaded function
Run Code Online (Sandbox Code Playgroud)

我明白这是因为decltype无法弄清楚你试图获得哪种类型的功能.但为什么没有另一种方法来实现这项工作,如下所示:

std::cout << decltype(test(double, double)) << std::endl;
Run Code Online (Sandbox Code Playgroud)

或这个:

double x = 5, y = 2;
std::cout << decltype(test(x, y)) << std::endl;
Run Code Online (Sandbox Code Playgroud)

由于函数不能简单地基于返回类型重载,不会将数据类型或实际变量传递给decltype调用足以告诉它应该检查哪些重载?我在这里错过了什么?

chr*_*ris 19

要根据您传递的参数类型确定函数的类型,您可以通过使用decltype和"调用"它们来"构建"返回类型,然后添加参数列表以分割整个类型一起.

template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);
Run Code Online (Sandbox Code Playgroud)

TestType<double, double>会导致类型int(double, double).你可以在这里找到一个完整的例子.

或者,您可能会发现尾随返回类型语法更具可读性:

template<typename... Ts>
using TestType = auto(Ts...) -> decltype(test(std::declval<Ts>()...));
Run Code Online (Sandbox Code Playgroud)