Guillaume Racicot Guillaume Racicot -4 years ago 39
C++ Question

Is there a way to decltype the result of a non callable function?

I would like to know if anyone has same trick to find the return type of the

find_me
function, without changing it's argument.

struct Stuck {
Stuck() = delete;
Stuck(Stuck&&) = delete;
Stuck(const Stuck&) = delete;
Stuck& operator=(Stuck&&) = delete;
Stuck& operator=(const Stuck&) = delete;
};

double find_me(Stuck);

int main() {
// This obviously don't work
decltype(find_me(Stuck{})) test1;
}


This is another shot I tried:

template<typename T>
struct ConvertTo {
operator T ();
}

int main() {
decltype(find_me(ConvertTo<Stuck>{})) test1;
}


The function
find_me
is overloaded many many times, and never actually implemented. I just want to know if there's a way to find the return type when the function has these form. I know that it would be possible to receive a pointer or a reference, this is what I'm already doing, but I would like to know if there also some trick to make this work.

If there is any, please tell me, and tell me why.

Thanks.

Answer Source

This works:

struct Stuck {
    Stuck() = delete;
    Stuck(Stuck&&) = delete;
    Stuck(const Stuck&) = delete;
    Stuck& operator=(Stuck&&) = delete;
    Stuck& operator=(const Stuck&) = delete;
};

double find_me(Stuck);
void find_me(double);

template <typename Ret>
Ret get_stuck_return_type(Ret (*)(Stuck));

int main() {
    decltype(get_stuck_return_type(find_me)) test1;
}

Coliru link: http://coliru.stacked-crooked.com/a/7eca81a13fae9de3

The reason why this works even when find_me is overloaded is that the template argument deduction will try each overload of find_me. If deduction succeeds with exactly one overload, that one is chosen for instantiating the template.

I assume this is a purely academic exercise, since a function taking an unconstructible type by value could serve no actual purpose.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download