为什么不能使用重载函数decltype工作? [英] Why can't decltype work with overloaded functions?
问题描述
decltype
失败,如果您调用它的函数重载,如下面的代码:
decltype
fails if the function you're calling it on is overloaded, as in this code:
#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
无法弄清哪个函数正在尝试获取类型。但是为什么没有其他方法来完成这项工作,例如:
I understand that this is because decltype
can't figure out which function you're trying to get the type of. But why isn't there another way to make this work, like this:
std::cout << decltype(test(double, double)) << std::endl;
或:
double x = 5, y = 2;
std::cout << decltype(test(x, y)) << std::endl;
由于函数不能基于返回类型重载,不会传递数据类型或实际变量到 decltype
调用足以告诉它应该检查哪个重载?
Since a function cannot be overloaded simply based on return type, wouldn't passing either datatypes or actual variables to the decltype
call be enough to tell it which of the overloads it's supposed to examine? What am I missing here?
推荐答案
要从你传递的参数的类型中找出函数的类型,你可以通过使用 decltype
和调用这些类型来构建返回类型,然后在参数列表中添加整个类型。
To figure out the type of the function from the type of the arguments you'd pass, you can "build" the return type by using decltype
and "calling" it with those types, and then add on the parameter list to piece the entire type together.
template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);
执行 TestType< double,double>
导致类型 int(double,double)
。您可以在此处找到完整示例。
Doing TestType<double, double>
will result in the type int(double, double)
. You can find a full example here.
或者,您可能会发现尾部返回类型语法更易读:
Alternatively, you might find the trailing return type syntax more readable:
template<typename... Ts>
using TestType = auto(Ts...) -> decltype(test(std::declval<Ts>()...));
这篇关于为什么不能使用重载函数decltype工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!