为什么 decltype 不能使用重载函数?

Why can't decltype work with overloaded functions?

本文关键字:重载 函数 decltype 不能 为什么      更新时间:2023-10-16

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;
}

结果:

error: decltype cannot resolve address of overloaded function

我知道这是因为decltype无法弄清楚您要尝试获得哪种功能。但是,为什么没有其他方法可以这样做:

std::cout << decltype(test(double, double)) << std::endl;

或以下:

double x = 5, y = 2;
std::cout << decltype(test(x, y)) << std::endl;

由于不能简单地基于返回类型对函数过载,因此将数据类型或实际变量传递给decltype调用是否足以告诉它应该检查的哪个过载?我在这里缺少什么?

从您要通过的参数类型中找出函数的类型,您可以使用decltype和"调用"与这些类型的"构建"返回类型然后添加参数列表以将整个类型拼凑在一起。

template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);

进行TestType<double, double>将导致int(double, double)类型。您可以在这里找到一个完整的示例。

另外,您可能会发现尾随的返回类型语法更可读:

template<typename... Ts>
using TestType = auto(Ts...) -> decltype(test(std::declval<Ts>()...));

我相信您可能正在寻找std::result_of<>

cppreference Page。

我找到了另一种方法:使用 std::declval生成假对象,然后使用 decltype

#include <type_traits>
#include <functional>
int myfunc(int a)
{
    return a;
}
float myfunc(float a)
{
    return a;
}
int main()
{
    decltype(myfunc(std::declval<float>())) a;  // return type
    std::function<decltype(a)(float)> fun;      // function type
    return 0;
}