Why can't decltype work with overloaded functions?

北慕城南 提交于 2019-12-18 02:46:38

问题


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

Results:

error: decltype cannot resolve address of overloaded function

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;

or this:

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

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?


回答1:


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...);

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>()...));



回答2:


I belive you may be looking for std::result_of<>

cppreference page.



来源:https://stackoverflow.com/questions/22291737/why-cant-decltype-work-with-overloaded-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!