#include <any>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x;
int y;
};
Point func() {
return {1, 2};
}
template <typename ... Ts>
auto sum(Ts ... ts) {
return (ts + ...);
}
int main()
{
// c++17 类型自动推导
vector a = {1, 2, 3};
// 结构化绑定, pair, array, struct
pair b(1, 2.3f);
auto&& [i, j] = b;
i = 2;
cout << b.first << endl; // 2
int array[3] = {1, 2, 3};
const auto& [x, y, z] = array;
cout << x << " " << y << " " << z << endl; // 1, 2, 3
const auto& [m, n] = func();
cout << m << " " << n << std::endl; // 1, 2
// if-switch语句初始化
// if (init; condition)
// int a = GetValue();
// if (a < 101) {
// cout << a;
// }
if (int a = 100; a < 101) {
cout << a << std::endl; // 100
}
string str = "Hi World";
if (auto [pos, _] = pair(str.find("Hi"), str.size()); pos != string::npos) {
std::cout << pos << std::endl; // 0
}
// 折叠表达式
any any_varibale {sum(1, 2, 3, 4, 5)};
cout << any_varibale.type().name() << " " << std::any_cast<int>(any_varibale) << endl; // 15
std::string d{"hello "};
std::string e{"world"};
cout << sum(d, e) << endl; // hello world
// std::any
any_varibale = 1;
cout << any_varibale.type().name() << " " << std::any_cast<int>(any_varibale) << endl;
any_varibale = 2.2f;
cout << any_varibale.type().name() << " " << std::any_cast<float>(any_varibale) << endl;
any_varibale = std::string("123");
cout << any_varibale.type().name() << " " << std::any_cast<std::string>(any_varibale) << endl;
}
// namespace 嵌套
namespace A {
namespace B {
namespace C {
void func();
}
}
}
namespace A::B::C {
void func();)
}
// inline variable in Header file "example.h":
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <atomic>
// function included in multiple source files must be inline
inline int sum(int a, int b)
{
return a + b;
}
// variable with external linkage included in multiple source files must be inline
inline std::atomic<int> counter(0);
#endif
// as_const可以将左值转成const类型, 比如用于lambda参数
// std::optional
// std::from_chars, std::to_chars