如何使用 result_of 而不是 decltype? [英] How Can I Use result_of Instead of decltype?
问题描述
在这个答案中,我创建了一个类型特征:
In this answer I create a type trait:
template<typename T>
using to_string_t = decltype(to_string(declval<T>()));
这很好用,但我最初打算使用 result_of
,现在让我很恼火,我不知道该怎么做.
This works just fine but I originally set out to use result_of
and now it's irking me that I can't figure out how to do it.
我试图用这样的东西替换上面的行:
I'm trying to replace the line above with something like this:
template<typename T>
using to_string_t = result_of<to_string(T)>;
但是我得到了一个编译器错误:
But I get a compiler error along the lines of:
错误 C2275:'T':非法使用此类型作为表达式
注意:参见'T'
的声明错误 C2974:std::result_of":_Fty"的模板参数无效,应输入类型
error C2275: 'T': illegal use of this type as an expression
note: see declaration of 'T'
error C2974: 'std::result_of': invalid template argument for '_Fty', type expected
我已经尝试了几个其他的 result_of
输入但没有成功,谁能帮我理解 result_of
在这里期望什么参数?
I've tried several other inputs to result_of
without success, can anyone help me understand what arguments result_of
is expecting here?
推荐答案
让我们修补它.std::result_of
只需要类型,它的结果应该从它的 type
内部 typedef 中检索,并且你需要 typename
来访问所说的 typedef,因为它取决于模板参数.
Let's patch it up. std::result_of
expects only types, its result should be retrieve from its type
inner typedef, and you need typename
to access said typedef because it depends on a template parameter.
template<typename T>
using to_string_t = typename std::result_of<decltype(std::to_string)(T)>::type;
^^^^^^^^ ^^^^^^^^ ^^^^^^
或者在 C++14 中,您可以删除 ::type
和 typename
:
Or in C++14, you can drop ::type
and 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
被重载了,所以我们需要通过将它转换为它的重载之一来消除歧义.
Right, std::to_string
is overloaded, so we need to disambiguate it by casting it to one of its overloads.
template<typename T>
using to_string_t = typename std::result_of<decltype(static_cast<
坚持住.我们需要它的返回类型来表达转换的目标类型.我们又回到了起点.
Hold on. We need its return type to express the destination type of the cast. We're back to our starting point.
std::result_of
不能处理重载的函数,因为在解决重载之前函数没有确定的类型.decltype
是这里唯一的解决方案,因为它确实应用了重载解析.
std::result_of
can't deal with overloaded functions, because the function has no definite type until the overload is resolved. decltype
is the only solution here, because it does apply overload resolution.
如果您想知道 std::result_of
如何有用,鉴于上述限制:它用于重载函子,即重载 ()
运算符的类几次.由于类的类型是已知的,并且不依赖于调用参数,std::result_of
可以工作.
If you're wondering how std::result_of
can be useful, given the above limitation : it's used for overloaded functors, i.e. classes that overload the ()
operator several times. As the type of the class is known, and does not depend on the call arguments, std::result_of
works.
...但不应该 std::to_string
总是返回一个 std::string
??
... But shouldn't std::to_string
always return a std::string
??
这篇关于如何使用 result_of 而不是 decltype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!