Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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

cppreference page.

I have found another way: use std::declval to generate a fake object, then use 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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top