如何使用result_of而不是decltype ?
How Can I Use result_of Instead of decltype?
在这个答案中,我创建了一个类型trait:
template<typename T>
using to_string_t = decltype(to_string(declval<T>()));
这工作得很好,但我最初打算使用result_of
,现在我不知道如何做到这一点,这让我很恼火。
我试着用这样的东西替换上面的行:
template<typename T>
using to_string_t = result_of<to_string(T)>;
但是我得到一个编译器错误沿着行:
错误C2275: 'T':非法使用此类型作为表达式
注:参见'T'的声明
错误C2974: 'std::result_of': '_Fty'的模板参数无效,类型预期
我已经尝试了其他几个输入到result_of
没有成功,谁能帮助我理解result_of
在这里期待什么参数?
让我们把它修补一下。std::result_of
只期望类型,它的结果应该从type
内部类型定义中检索,并且您需要typename
来访问所述类型定义,因为它依赖于模板参数。
template<typename T>
using to_string_t = typename std::result_of<decltype(std::to_string)(T)>::type;
^^^^^^^^ ^^^^^^^^ ^^^^^^
或者在c++ 14中,可以去掉::type
和typename
:
template<typename T>
using to_string_t = std::result_of_t<decltype(std::to_string)(T)>;
^^
好吗?
main.cpp:5:68: error: decltype cannot resolve address of overloaded function
对,std::to_string
是重载的,所以我们需要通过将它强制转换为它的重载之一来消除它的歧义。
template<typename T>
using to_string_t = typename std::result_of<decltype(static_cast<
等。我们需要它的返回类型来表示强制转换的目标类型。我们又回到了起点。
std::result_of
不能处理重载函数,因为在解决重载之前函数没有明确的类型。decltype
是这里唯一的解决方案,因为它应用重载解析。
如果你想知道std::result_of
是如何有用的,考虑到上面的限制:它用于重载的函子,即重载()
操作符多次的类。因为类的类型是已知的,并且不依赖于调用参数,所以std::result_of
可以工作。
…但是std::to_string
不应该总是返回std::string
吗??
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- Usages of std::move
- C++decltype和圆括号-为什么
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如何从"decltype()"获取函数参数的数量<funtion>?
- Confusion: decltype vs std::function
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- decltype(1, t) 应该是 l 值引用吗?(编译器不同意)
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- decltype of boost::make_zip_iterator?
- C++11 decltype of member
- Purpose of decltype-specifier