alignas & alignof
alignas声明结构体对齐的字节数
glignas返回结构体对齐的字节数(默认的是结构体内部最长的)
truct Foo
{
int i;
float f;
char c;
};
//alignof(Foo) == 4
struct Empty {};
//alignof(Empty) == 1
struct alignas(64) Empty64 {};
//alignof(Empty64) == 64
struct alignas(1) Double {
double d;
};
//alignof(double) == 8
struct Obj {
char a;
int b;
};
//sizeof(Obj) == 8
//alignof(Obj) == 4
//alignof(char) == 1
//alignof(int*) == 8(64) 4(32)
constexpr
https://blog.csdn.net/qq_22274565/article/details/78719951
decltype
decltype与auto关键字一样,用于进行编译时类型推导,不过它与auto还是有一些区别的。decltype的类型推导并不是像auto一样是从变量声明的初始化表达式获得变量的类型,而是总是以一个普通表达式作为参数,返回该表达式的类型,而且decltype并不会对表达式进行求值。
推导出表达式类型
int i = 4;
decltype(i) a; //推导结果为int。a的类型为int。
与using/typedef合用,用于定义类型。
using size_t = decltype(sizeof(0));//sizeof(a)的返回值为size_t类型
using ptrdiff_t = decltype((int*)0 - (int*)0);
using nullptr_t = decltype(nullptr);
vector<int >vec;
typedef decltype(vec.begin()) vectype;
for (vectype i = vec.begin; i != vec.end(); i++)
{
//...
}
这样和auto一样,也提高了代码的可读性。
重用匿名类型
在C++中,我们有时候会遇上一些匿名类型,如:
struct
{
int d ;
doubel b;
}anon_s;
而借助decltype,我们可以重新使用这个匿名的结构体:
decltype(anon_s) as ;//定义了一个上面匿名的结构体
泛型编程中结合auto,用于追踪函数的返回值类型
这也是decltype最大的用途了。
template <typename _Tx, typename _Ty>
auto multiply(_Tx x, _Ty y)->decltype(_Tx*_Ty)
{
return x*y;
}
const_cast
dynamic_cast
enum
c++11中新版enum与class连用
引用时需要加前缀,原本的enum不受命名空间的影响。
如:
enum class color{ Red, Green, Blue};
int main() {
color r = color::Blue;
switch (r) {
case color::Blue:
std::cout << "Blue\n";
case color::Red:
std::cout << "Red\n";
case color::Green:
std::cout << "Green\n";
}
}