如何定义模板类中方法的返回类型
How to typedef the return type of a method from a template class?
我有一个模板类Helper
,看起来像这样:
template< typename Mapper >
class Helper
{
public:
using mappedType = ... ;
};
我需要mappedType
是Mapper
类中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));
};
相关文章:
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 具有引用返回类型的重写方法上的协变返回类型无效
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- Java 调用 dll 字符串返回类型方法
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 如何拥有两个名称相同但返回类型不同的纯虚拟方法
- 可能从单个方法返回不同类型的对象
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 将返回类型推断为模板参数类型方法
- dlsym() 解决方法返回类型
- 我如何根据某些模板参数影响模板类方法的返回类型
- 如何检查模板类方法返回类型
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 类成员方法 - 返回类型模板
- C++中具有多态模板类的未知方法返回类型
- 是否可以使用Boost概念检查库验证方法返回类型
- 使用不同方法返回类型的C++模板类设计