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

时间:2016-11-17 12:56:28

标签: c++ types c++14 return-type-deduction

我有一个模板化的类Helper,如下所示:

template< typename Mapper >
class Helper
{
public:

   using mappedType = ... ;

};

我需要mappedType作为map(const int&)类中Mapper方法返回的类型。给出Mapper的有效类型,如下所示:

class DMapper
{
public:

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

Helper<DMapper>::mappedType应为double。有没有办法在没有实例化Mapper

的情况下做到这一点

我最接近的是:

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

但是在这种情况下没有定义type

修改

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

3 个答案:

答案 0 :(得分:33)

您可以使用std::declvaldecltype中使用成员函数而无需创建实例:

using mappedType = decltype(std::declval<Mapper>().map(0));

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

using mappedType = decltype(std::declval<Mapper>().map(std::declval<int>()));

答案 1 :(得分:15)

  

我最接近的是

     

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

你几乎得到了它。

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

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

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

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

答案 2 :(得分: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));
};