c++11 decay/decltype/declval
2022/4/28 12:12:41
本文主要是介绍c++11 decay/decltype/declval,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
decay
std::decay对类型进行退化处理。
a. T为数组U或数组U引用,则type为U*.
b. T为函数时,则type为std::add_pointer
c. 其它类型则移除cv限定符(const和volatile),则type为std::remove_cv<std::remove_reference
#include <type_traits> typedef std::decay<int>::type A; // int typedef std::decay<int&>::type B; // int typedef std::decay<int&&>::type C; // int typedef std::decay<const int&>::type D; // int typedef std::decay<int[2]>::type E; // int* typedef std::decay<int(int)>::type F; // int(*)(int) typedef int X[3]; int main() { std::cout << std::boolalpha; std::cout << "typedefs of int:" << std::endl; std::cout << "A: " << std::is_same<int,A>::value << std::endl; std::cout << "B: " << std::is_same<int,B>::value << std::endl; std::cout << "C: " << std::is_same<int,C>::value << std::endl; std::cout << "D: " << std::is_same<int,D>::value << std::endl; std::cout << "E: " << std::is_same<int,E>::value << std::endl; std::cout << "F: " << std::is_same<int,F>::value << std::endl; return 0; }
declval
std::declval 返回对象的右值引用,不管对象是否有构造函数,一般配合decltype使用。This function shall only be used in unevaluated operands (such as the operands of sizeof and decltype).T may be an incomplete type.
This is a helper function used to refer to members of a class in unevaluated operands ** , especially when either the constructor signature is unknown or when no objects of that type can be constructed (such as for abstract base classes).
#include <utility> // std::declval #include <iostream> // std::cout struct A { // abstract class virtual int value() = 0; }; class B : public A { // class with specific constructor int val_; public: B(int i,int j):val_(i*j){} int value() {return val_;} }; int main() { decltype(std::declval<A>().value()) a; // int a decltype(std::declval<B>().value()) b; // int b decltype(B(0,0).value()) c; // same as above (known constructor) a = b = B(10,2).value(); std::cout << a << '\n'; return 0; }
decltype
delctype 可以在编译期内推导表达式所得值的类型。
template<typename T1, typename T2> void sum(T1 &t1, T2 &t2, decltype(t1 + t2) &s) { s = t1 + t2; } template<typename T1, typename T2> auto sum(T1 &t1, T2 &t2) ->decltype(t1 + t2)) { return t1 + t2; } int hash(char*); map<string, decltype(hash(nullptr))> mm; // 动态指定hash()返回类型,方便后续维护
这篇关于c++11 decay/decltype/declval的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升