为什么 decltype 不能使用重载函数?
Why can't decltype work with overloaded functions?
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;
}
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?