c++11:std::declval、decltype

编程入门 行业动态 更新时间:2024-10-25 10:33:53

c++11:<a href=https://www.elefans.com/category/jswz/34/1764904.html style=std::declval、decltype"/>

c++11:std::declval、decltype

1、decltype是类型推导

#include <iostream>struct A { double x; };
const A* a;decltype(a->x) y;       // y 的类型是 double(其声明类型)
decltype((a->x)) z = y; // z 的类型是 const double&(左值表达式)template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) // 返回类型依赖于模板形参
{                                     // C++14 开始可以推导返回类型return t+u;
}int main() 
{int i = 33;decltype(i) j = i * 2;std::cout << "i = " << i << ", "<< "j = " << j << '\n';auto f = [](int a, int b) -> int{return a * b;};decltype(f) g = f; // lambda 的类型是独有且无名的i = f(2, 2);j = g(3, 3);std::cout << "i = " << i << ", "<< "j = " << j << '\n';
}

运行结果:
2、std::declval

inline T &&std::declval<T>()

将任意类型 T 转换成引用类型,令在 decltype 表达式中不必经过构造函数就能使用成员函数。

// declval example
#include <utility>      // std::declval
#include <iostream>     // std::coutstruct A {              // abstract classvirtual int value() = 0;
};class B : public A {    // class with specific constructorint val_;
public:B(int i,int j):val_(i*j){}int value() {return val_;}
};int main() {decltype(std::declval<A>().value()) a;  // int adecltype(std::declval<B>().value()) b;  // int bdecltype(B(0,0).value()) c;   // same as above (known constructor)a = b = B(10,2).value();std::cout << a << '\n';return 0;
}

运行结果:

更多推荐

c++11:std::declval、decltype

本文发布于:2023-06-26 04:10:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/889079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   decltype   declval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!