3

I am trying to get the return type of a function with const/non const overloads.

struct TestClass {
    const int* getPtr() const { return ptr; }
    int* getPtr() { return ptr; }
private:
    int* ptr;
};

using return_ptr_type = typename std::invoke_result<decltype(&TestClass::getPtr), TestClass>::type;
static_assert(std::is_same<return_ptr_type, int*>::value);

Compiler complains that it cannot resolve address of overloaded function. I understand why this happens, but not how to fix it.

Note: I see other questions on stack overflow on how to resolve between overloads, but they deal with overloads with different function arguments, not const overloads.

Sway
  • 317
  • 1
  • 7

1 Answers1

2

In decltype(&TestClass::getPtr) overload resolution won't happen; there're even no context for compilers to choose one.

You can get the return type by calling getPtr() on const or non-const object, to make overload resolution taking effect. e.g.

using return_ptr_type1 = decltype(std::declval<TestClass>().getPtr());
static_assert(std::is_same<return_ptr_type1, int*>::value);

using return_ptr_type2 = decltype(std::declval<const TestClass>().getPtr());
static_assert(std::is_same<return_ptr_type2, const int*>::value);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405