如何从模板类中键入方法的返回类型?

Dr_*_*Sam 18 c++ types return-type-deduction c++14

我有一个模板化的类Helper,看起来像这样:

template< typename Mapper >
class Helper
{
public:

   using mappedType = ... ;

};
Run Code Online (Sandbox Code Playgroud)

我需要mappedType是类中map(const int&)方法返回的Mapper类型.给出Mapper类似以下的有效类型:

class DMapper
{
public:

    double map(const int& val){ ... }
};
Run Code Online (Sandbox Code Playgroud)

Helper<DMapper>::mappedType应该是double.有没有办法在没有实例化的情况下做到这一点Mapper

我得到的最接近的是:

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

type在这种情况下没有定义.

编辑:

如果我可以避免使用伪参数int,那就更好了(在我的具体代码中,参数并不那么简单).

was*_*ful 33

您可以std::declvaldecltype不创建实例的情况下使用成员函数:

using mappedType = decltype(std::declval<Mapper>().map(0));
Run Code Online (Sandbox Code Playgroud)

std::declval 也可以用于参数:

using mappedType = decltype(std::declval<Mapper>().map(std::declval<int>()));
Run Code Online (Sandbox Code Playgroud)


Ser*_*gey 15

我得到的最接近的是

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

你几乎得到了它.

自动声明的this指针在非常量类方法中不是常量,所以你的

decltype(&Mapper::map)(Mapper const*, const int&)
Run Code Online (Sandbox Code Playgroud)

Mapper课堂上的任何方法都不匹配.const从第一个参数中删除限定符,并且您的result_of解决方案将在没有实例化和伪参数的情况下工作:

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


Leo*_*eon 5

假设这Mapper::map不是重载方法,其返回类型可以自动解析,如下所示:

template< typename Mapper >
class Helper
{
private:
    template<class R, class... T>
    static R resolveReturnType(R (Mapper::*)(T...));

    template<class R, class... T>
    static R resolveReturnType(R (Mapper::*)(T...) const);

public:
    using mappedType = decltype(resolveReturnType(&Mapper::map));
};
Run Code Online (Sandbox Code Playgroud)