文章目录
一、关键字
1.1 alignas
struct alignas(8) S {};
struct alignas(1) U { S s; }; // 错误:若无 alignas(1) 则 U 的对齐将为 8
1.2 alignof
#include <iostream>
struct Foo {
int i;
float f;
char c;
};
struct Empty {};
struct alignas(64) Empty64 {};
int main()
{
std::cout << "Alignment of" "\n"
"- char : " << alignof(char) << "\n"
"- pointer : " << alignof(int*) << "\n"
"- class Foo : " << alignof(Foo) << "\n"
"- empty class : " << alignof(Empty) << "\n"
"- alignas(64) Empty: " << alignof(Empty64) << "\n";
}
1.3 decltype
1.4 auto
int a = 10;
auto au_a = a; //自动类型推断,au_a为int类型
cout << typeid(au_a).name() << endl;
1.5 static_assert
static_assert(常量表达式,"提示语");
1.6 noexcept
1.7 constexpr
int i;
const int size = i;
int arr[size]; //error,size不是常量表达式,不能在编译期确定
constexpr auto size = 10;
int arr[size]; //OK,size时常量表达式
int i;
constexpr int size = i; // error,i不能在编译期确定
constexpr int foo(int i) {
return i + 5;
}
int main() {
int i = 10;
std::array<int, foo(5)> arr; // OK,5是常量表达式,计算出foo(5)也是常量表达式
foo(i); // Call is Ok,i不是常量表达式,但仍然可以调用(constexpr 被忽略)
std::array<int, foo(i)> arr1; // Error,但是foo(i)的调用结果不是常量表达式了
}
1.8 thread_local
二、预定义宏
2.1 __STDC_HOSTED__
2.2 __STDC__
2.3 __STDC__VERSION__
2.4 __STDC_ISO_10646__
2.5 __func__
2.6 _Pragma
2.7 __VA_ARGS__
三、类相关
3.1 final
3.2 override
3.3 继承构造函数
#include <string>
class A
{
public:
A(int i){};
A(std::string str){};
};
class B : A
{
public:
using A::A;
};
int main(int argc, char const *argv[])
{
B b1(123); // ok
B b2("abc"); // ok
return 0;
}
四、其他
4.1 lambda
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
return a < b;
}
int main()
{
vector<int> myvec{ 3, 2, 5, 7, 3, 2 };
vector<int> lbvec(myvec);
sort(myvec.begin(), myvec.end(), cmp); // 旧式做法
cout << "predicate function:" << endl;
for (int it : myvec)
cout << it << ' ';
cout << endl;
// Lambda表达式
sort(lbvec.begin(), lbvec.end(), [](int a, int b) -> bool { return a < b; });
cout << "lambda expression:" << endl;
for (int it : lbvec)
cout << it << ' ';
}