如何使用result_of而不是decltype ?

How Can I Use result_of Instead of decltype?

本文关键字:decltype of 何使用 result      更新时间:2023-10-16

在这个答案中,我创建了一个类型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中,可以去掉::typetypename:

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吗??