3

下面的示例在我尝试过的所有编译器中都失败了:gcc-8.2、clang-8.0(两个选项都已尝试)--std=c++17std=c++2azapcc-2017.08。

从我的角度来看,代码示例是有效的,应该被编译。或者,至少,应该有一个更全面的错误。它看起来确实像 std 库中的一个错误,没有涵盖result_of. 我错了吗?

#include <type_traits>
using namespace std;
struct bar {
    int a;
    long b;
};

template<auto M>
struct foo {
    static auto q(bar & b) {
        return b.*M;
    }
};

template<auto M>
auto qoo(bar & b) {
    return b.*M;
}


// error: 'type' in 'class std::result_of<int(bar&)>' does not name a type
using f = typename result_of<decltype(foo<&bar::a>::q)>::type;
// error: 'type' in 'class std::result_of<int(bar&)>' does not name a type
using q= typename result_of<decltype(qoo<&bar::a>)>::type;
4

3 回答 3

4

result_of_t<F(Args...)>意思是“调用/调用的结果FArgs...

result_of_t<int(bar&)>int意思是“用”调用的结果bar&。这不存在,因为你不能int用任何东西来调用。

result_of不是“从函数类型提取返回类型”。

于 2018-11-08T18:08:51.600 回答
3

尝试

using f = typename std::result_of<decltype(&foo<&bar::a>::q)(bar&)>::type;

using q= typename std::result_of<decltype(&qoo<&bar::a>)(bar&)>::type;

正如 TC 更好地解释的那样,typeinstd::result_of是在使用某些参数类型调用时从可调用类型返回的类型。

如果你写

std::result_of<decltype(foo<&bar::a>::q)>

你只传递给std::result_of可调用的类型(几乎:你还需要一个&before foo);您还必须传递参数的类型(只有一个参数,在这种情况下:bar引用),所以

std::result_of<decltype(&foo<&bar::a>::q)(bar&)>
于 2018-11-08T18:11:09.973 回答
1

根据我的经验,确实没有什么result_of可以做而decltype不能(或result_of_t有助于简化您的代码):如何使用 result_of 而不是 decltype?

在这种情况下也是如此, wheredecltypedeclval会给你一个比 更简单的结果result_of

using f = decltype(foo<&bar::a>::q(declval<bar&>()));
using q = decltype(qoo<&bar::a>(declval<bar&>()));

Live Example

于 2018-11-08T18:31:34.550 回答