我不理解 std::result_of 和 decltype 的这些用法
I'm not understanding these uses of std::result_of and decltype
在我的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_of
按decltype
声明以下方式:
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;
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- C++decltype和圆括号-为什么
- 这个指针在c++中的用法
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如何从"decltype()"获取函数参数的数量<funtion>?
- Confusion: decltype vs std::function
- decltype(1, t) 应该是 l 值引用吗?(编译器不同意)
- 当C++中需要自动删除时,这是静态的正确用法吗?
- libstdc++ 文件系统中未初始化的用法?
- 复制和交换习惯用法与移动操作之间的交互
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 命名参数习惯用法和(抽象)基类
- 省略号在C++中的所有用法
- () 在 C++ 11 中的特殊而奇怪的用法?
- 构造函数的用法
- 模板类中自动的类用法不完整
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 我不理解 std::result_of 和 decltype 的这些用法
- std::vector<decltype(iter)>-decltype的有效用法
- C++11 decltype的启示用法