Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

c++ - Why can't decltype work with overloaded functions?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...