Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return type of overloaded method in C++?

I have a struct somewhere:

struct A {
  ComplicatedType1 f();
  ComplicatedType2 f(int);
};

I want to get the return-type of f() using compile-time helpers. I'm trying std::result_of<>:

using Type = std::result_of<decltype(&A::f)()>::type;

But the compiler gives me a reasonable error: "reference to overloaded function could not be resolved".

So I go to SO and see this accepted and upvoted answer, which suggest to make a static_cast<ComplicatedType1 (A::*)()>(&A::f) - but I don't have a ComplicatedType1 at this point. I'm stuck in a recursion.


How to get ComplicatedType1 inside my using expression with a minimum of code?

like image 775
abyss.7 Avatar asked Nov 08 '15 10:11

abyss.7


1 Answers

Thats's a job for decltype + declval

#include <iostream>
#include <type_traits>
#include <utility>

struct ComplicatedType1 {};
struct ComplicatedType2 {};

struct A {
  ComplicatedType1 f();
  ComplicatedType2 f(int);
};

int main()
{
    using Type = decltype(std::declval<A>().f());
    static_assert(std::is_same<Type,ComplicatedType1>::value,"Oops");
}

live at Coliru

EDIT: Changed to get return type of f() (instead of f(int)) and to c++11 (instead of c++14) on Coliru

like image 154
decltype_auto Avatar answered Sep 28 '22 00:09

decltype_auto