元编程通过模板推演和编译器数值计算,来保证代码生成的安全性和提升程序运行性能。
#include <iostream>
#include <limits>
using namespace std;
template<typename T>
inline void test(const T& x)
{
cout<<
"x = "
<< x <<
" ("
;
auto oldp
=
cout.precision(numeric_limits<T>::digits10
+
1
);
cout<<x<<
")"
<<endl;
cout.precision(oldp);
}
int
main()
test(
1.f
/
3.f
1.
3.0
3.0l
struct simple_point
#ifdef __cplusplus
simple_point(double x, double y): x(x),y(y) {}
simple_point()
default;
simple_point(initializer_list<double> il)
auto it
begin(il);
x
*
it;
y
next
(it);
#endif
double x,y;
};
simple_point p1{
,
7.1
}, p2;
static_assert(std::is_trivially_copyable
<simple_point>::value,
"simple_point is not as simple as you think "
"and cannot be memcpyd!"
std::memcpy (&p2, &p1, sizeof(p1));
#include <vector>
#include <optional>
optional <double> square_root(double x)
if
(x <
0.0
)
return
nullopt;
else
sqrt(x);
vector <double> v
4.0
-
0.09
0.25
for
(double d : v)
(auto s
square_root(d); s)
cout <<
"Square root of "
<< d <<
" is "
<<
s <<
'\n'
cout << d <<
" has no square root.\n"
tuple
<matrix, vector> lu(const matrix& A)
matrix LU(A);
vector p(n);
... some computations
<matrix, vector>(LU, p);
通过类型参数推导简化
make_tuple(LU,p);
C++17 进一步简化
auto lu(const matrix& A)
...
{LU,p};
make_tuple
auto t
make_tuple (LU, p,
7.3
9
, LU
p,
2.0
9.0i
C++17 能直接从构造函数推导
t{LU, p,
C++17 甚至都不用使用tuple进行存储
auto [LU,p]
lu(A);
#include <variant>
using my_variant
variant<
,double,string>;
my_variant var;
var
3
4.2
"Text"
string s
get<
2
>(var);
s
get<string>(var);
auto find_ints(const vector<
any
>& v)
vector<
> vi;
(const
& a : v)
(a.
type
()
typeid(
))
vi.push_back( any_cast<
>(a) );
vi;
void print_some_string(string_view sv)
cout << sv <<
支持的类型有函数,仿函数,lambdas。
double add(double x, double y)
y;
using bin_fun
function<double(double, double)>;
bin_fun f
&add;
"f(6, 3) = "
<< f(
6
) << endl;
using namespace std::chrono;
见到这个标志查文档吧
C++11就有介绍
threads
future
promise
async
atomic
mutex
C++14
shared_timed_mutex
C++17
shared_mutex
C++20 协程
co_await、co_yield、co_return 三个语法特征
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课
sunsjw std::memcpy 是要加哪个头文件吗? 我这里include 只能memcpy不能 std::memcpy