Search code examples
c++templatespolymorphismc++17decltype

Return type of overloaded named non-member function with invoke_result


Given a number of overloaded functions taking differently-typed parameters, is there a way to get the return type or one of the parameter types for a particular overload, within a templated context, at compile time? Consider for example this situation where the overloaded function takes a parameter reference as an out-value:

struct struct_a { };
struct struct_b { };
struct struct_c { };

float process(struct_a) { return 5.0f;  }
bool  process(struct_b) { return true; }
int   process(struct_c) { return -1; }

void process_in_place(struct_a, float& out) { out = 5.0f;  }
void process_in_place(struct_b, bool& out) { out = true;  }
void process_in_place(struct_c, int& out) { out = -1;  }

template<typename T>
void do_process(T val)
{
    auto result1 = process(val);
    std::cout << result1 << std::endl;

    // ???
    //using post_process_type = std::invoke_result_t<decltype(process)&(std::declval<T>)>;
    // ???
    post_process_type result2;
    process_in_place(val, result2);
}

int main()
{
    do_process(struct_a());
    do_process(struct_b());
    do_process(struct_c());
}

How would I know what type the out-param should be prior to invoking whichever version of process_in_place is ultimately selected?


Solution

  • using post_process_type = decltype(process(std::declval<T>()));
    

    This will do. decltype will just look at the return type after overload resolution selects the right process.