我不理解 std::result_of 和 decltype 的这些用法

I'm not understanding these uses of std::result_of and decltype

本文关键字:decltype 用法 of 不理解 std result      更新时间:2023-10-16

在我的Visual Studio Project上,我有以下操作,效果很好:

template <typename T>
void function(T type)
{
    std::result_of<T()>::type myVar = 5; // This compiled fine with Visual Studio, 
but with GCC it shows the following errors:
    //error: dependent-name ‘std::result_of<T()>::type’ is parsed as a non-type, 
    //but instantiation yields a type. note: say ‘typename std::result_of<T()>::type’ if a type is meant
}
int main() {
    auto lambda = []() { return float(); };
    function(lambda);
    return 0;
}

我只想了解,编译器坚持认为我将std :: result_of带有" typeName",因为它可能是模棱两可的,在std :: result_of中可以返回类,然后:: type可能是一个该课程的成员?这就是为什么它坚持添加打字名称?如果是这种情况,那么为什么Visual Studio允许它?是不合规吗?

另外,由于我已经阅读了usport_of在C 14或C 17处被弃用,所以我想尝试使用更通用的声明,它应该在更多情况下起作用。所以我尝试了:

template <typename T>
void function(T type)
{
decltype(T()) myVar = 5; // Error, use of deleted function‘main()::<lambda()>::<lambda>()’  main.cpp    
}

因此,我知道lambda具有删除的默认构造函数和复制分配运算符,但是在这种情况下,我真的认为,当将lambda传递给此模板功能时,lambda的复制构造函数称为它。然后,当我执行DECTTYPE(t())时,我认为这会调用其operator()函数。我不明白为什么它说有关已删除函数的话。

最后我尝试了:

decltype(std::declval<T()>) myVar = 5;

,因为我认为可以将Declval使用好像创建了您所做的任何呼叫的假实例,至少这就是向我解释的方式。这也失败了错误:

"类型'main()::&amp;&amp;’引用的初始化无效 从类型的" int"

的表达

result_of

首先,GCC编译器需要std::result_of之前的关键字typename,因为后者的返回值是类。您必须指示它使用其类型来声明新变量。

关于您的评论:

另外,因为我已经阅读了该结果_OF是从C 14或C 17

拒绝的

std::result_of在C 17处被弃用(请参见此处),并由新介绍的std::invoke_result,因此,如果您有一个合规编译器,则可以使用它。

electType

由于std::result_ofdecltype声明以下方式:

  template<typename _Signature>
  struct result_of;
  template<typename _Functor, typename... _ArgTypes>
  struct result_of<F(Args...)> {
      typedef decltype( std::declval<F>()(std::declval<Args>()...) ) type;
  };

您可以使用类似的定义:

decltype( std::declval<T>()() ) myVar = 5;