Dr_Sam Dr_Sam - 21 days ago 8
C++ Question

How to typedef the return type of a member function from a template class?

I have a templated class

Helper
which looks like this:

template< typename Mapper >
class Helper
{
public:

using mappedType = ... ;

};


I would need
mappedType
to be the type returned by the
map(const int&)
function in the
Mapper
class. Given a valid type for
Mapper
like the following:

class DMapper
{
public:

double map(const int& val){ ... }
};


Helper<DMapper>::mappedType
should be
double
. Is there a way to do that without instantiating a
Mapper
?

The closest I got is:

using mappedType = typename std::result_of<decltype(&Mapper::map)(Mapper const*, const int&)>::type;


But
type
is not defined in this case.

EDIT:

If I can avoid using a dummy argument for the
int
, that would be even better (in my concrete code, the argument is not that simple).

Answer

The closest I got is

using mappedType = typename std::result_of<decltype(&Mapper::map)(Mapper const*, const int&)>::type;

You almost got it.

Auto-declared this pointer is not constant in non-constant class methods, so your

decltype(&Mapper::map)(Mapper const*, const int&)

does not match any method in Mapper class. Remove const qualifier from the first argument, and your result_of solution will work without instancing and dummy arguments:

using mappedType = typename std::result_of<
    decltype(&Mapper::map)(Mapper /*no const here*/ *, const int&)
>::type;