如何定义模板类中方法的返回类型

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

本文关键字:方法 返回类型 何定义 定义      更新时间:2023-10-16

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

template< typename Mapper >
class Helper
{
public:
   using mappedType = ... ;
};

我需要mappedTypeMapper类中map(const int&)方法返回的类型。给定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的虚拟参数,那就更好了(在我的具体代码中,参数不是那么简单)。

您可以使用std::declval来使用decltype中的成员函数,而无需创建实例:

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

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

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

最接近的是

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;

假设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));
};