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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-01使用 SVN合并操作时,怎么解决冲突的情况?-icode9专业技术文章分享
- 2025-01-01告别Anaconda?试试这些替代品吧
- 2024-12-31自学记录鸿蒙API 13:实现人脸比对Core Vision Face Comparator
- 2024-12-31自学记录鸿蒙 API 13:骨骼点检测应用Core Vision Skeleton Detection
- 2024-12-31自学记录鸿蒙 API 13:实现人脸检测 Core Vision Face Detector
- 2024-12-31在C++中的双端队列是什么意思,跟消息队列有关系吗?-icode9专业技术文章分享
- 2024-12-31内存泄漏(Memory Leak)是什么,有哪些原因和优化办法?-icode9专业技术文章分享
- 2024-12-31计算机中的内存分配方式堆和栈有什么关系和特点?-icode9专业技术文章分享
- 2024-12-31QT布局器的具体使用原理和作用是什么?-icode9专业技术文章分享
- 2024-12-30用PydanticAI和Gemini 2.0构建Airflow的AI助手