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()返回类型,方便后续维护
posted on 2022-04-28 10:53 Ultraman_X 阅读(527) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话