0%

c++11

c11的一些新特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <algorithm>
#include <boost/filesystem.hpp>
#include <cstdio>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <regex>
#include <string>
#include <tuple>
#include <typeinfo>
using namespace std;


//------泛型------
template<class T>
void Out(T ta){//普通通用模版
std::cout<<"<T>L"<<ta<<std::endl;
}
template<>//模版的特例化/具体化 <>不能少 本质上还是个模版
void Out(int ta){
std::cout<<"<>L"<<ta<<std::endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
  template
void Out(int ta);//模版的显示实例化 本质是个函数 //用来做声明类型用的,只需要声明就行 不要跟下边的Out(int ta)搞成一个,下边的Out(int ta)不要也可以的

void Out(int ta){
std::cout<<"temp"<<ta<<std::endl;
}

template<class T1,class ...Args>
void Out(T1 t1 ,Args... t2){
std::cout<<"T"<<t1<<std::endl;
Out(t2 ...);
}
//模版的实例化和特例化/具体化
//函数同名(重载)时,调用优先级通常为:普通函数 >显式具体化(template specilazation)>显式实例化>一般模版函数
//实例化:是对模版函数的类型实例化 本质是个函数
//特例化:是对模版函数的类型指定特定类型 本质还是个模版
//-------泛型-------




/***
* 使用function类模版 多态函数包装器 类似函数指针 //闭包(仿函数,std::bind,lammbda)实现的一种.闭包:带有上下文状态的函数
* */
std::function<void(int, string)> fun_obj;

/***
* 普通函数
* */
void fun1(int a, string str) {
std::cout << "a:" << a << std::endl;
std::cout << "std:" << str << std::endl;
}

/***
* c++11 auto + decltype
* */
auto fun2(int a) -> decltype(a) { return a; }

/***
* c++ typeid() 数据类型判断
*/

template <typename T>
void typeid_fun(T t)
{
if(typeid(t) == typeid(int))
std::cout<<"int"<<std::endl;
if(typeid(t) == typeid(string))
std::cout<<"string"<<std::endl;
if(typeid(t) == typeid(vector<int>))
std::cout<<"vector<int>"<<std::endl;
if(typeid(t) == typeid(vector<vector<int>>))
std::cout<<"vector<vector<int>>"<<std::endl;
}


/***
* 宏定义简化函数
* */
#define pout(x) \
do { \
std::cout << x << std::endl; \
} while (0);

template <typename T>
void fun4(T t) {
pout(t);
}

/**
* 使用模版嵌套类型
* */

template <typename T1>
void TestCountIf(T1 &v1) {
int num = std::count_if(v1.begin(), v1.end(), [&](typename T1::value_type a) {
std::cout << a << std::endl;
return true;
});
std::cout << "CN:" << num << std::endl;
}

/***
* 使用 std::initializer_list 实现可变参数
* */
template <typename T>
void p(std::initializer_list<T> l) {
for (auto x : l) {
pout(x)
}
}

/***
* 模版可变参数
* */
void p11() {}

template <typename T1, typename... T2>
void p11(T1 t1, T2... args) {
pout(t1);
p11(args...);
}
// 模版可变参数

class CT {
public:
CT(){pout("CT constr")} CT(int a) : CT() {}
~CT() {}
};

/***
* c++11元组
* c++11正则表达式
* 左值 右值 左值引用 右值引用
* */

void GetFiles() {}

/***
* c++11 只能指针
* */
void Ptr() {
unique_ptr<int> up1(new int(111));
pout(*up1);

shared_ptr<int> sp1(new int(222));
shared_ptr<int> sp2 = sp1;

pout(*sp1);
pout(*sp2);
pout(sp1.use_count());
sp2.reset();
pout(sp1.use_count());
}

void Jp(int a) { pout(a); }

/***
* c++11 右值引用
* */
void RValue(int&& v) {
pout(v);
pout(&v);
}
/*

*/
void Value(int& v) {
pout(v);
pout(&v);
}

/**
* execption div 0 execption
* */
void Execp() {
try {
/* code */
int b = 0;
if (!b) {
throw - 1;
}
int div = 10 / b;
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
}

void SetMap() {
std::map<int, string> m;
m[1] = "h1";
m[2] = "h2";
pout(m.size())
}



int main() {

std::vector<int>v1 = {1,2,3,4,5};
TestCountIf(v1);


vector<int>vi;
typeid_fun(vi);
vector<vector<int>>vvi;
typeid_fun(vvi);


SetMap();
//Execp();
RValue(123 + 123);
int xv = 123;
Value(xv);
RValue(std::move(xv));

int ia = 1;
int ib = 2;
pout(std::plus<int>()(ia, ib));

std::list<int> sl = {3, 7, 2, 5, 9, 4};
auto max_it = std::max_element(sl.begin(), sl.end());
pout(*max_it);

Ptr();

// std::invoke(Jp, 999);
// std::invoke(Ptr);

std::cout << "hello" << std::endl;
fun_obj = fun1;
fun_obj(1, "helo");

string str = "hello";
auto s = str;
std::cout << "s:" << s << std::endl;
decltype(s) s2 = s;
std::cout << "type:" << s2 << std::endl;

auto a1 = fun2(10);
std::cout << a1 << std::endl;
pout("helllo");

p<int>({1, 2, 3, 4, 5});

p11<int>(11, 22, 33, 44);

CT* ct = new CT(111);

/*
std::string root_dir = "/Users/jay/Work";
for (auto x : boost::filesystem::directory_iterator(root_dir)) {
pout(x);
}
namespace fs = boost::filesystem;
fs::path p(root_dir);
fs::path rs = p.root_directory();
fs::path rs1 = p.root_name();
fs::path rs2 = p.root_path();
pout(p.root_directory());
pout(p.root_name());
pout(p.root_path());
fs::path cs = fs::current_path();

for (auto x : fs::recursive_directory_iterator("/Users/jay/Data/wenzhou")) {
// pout(x)
if (fs::status(x).type() == fs::file_type::directory_file) {
pout(x)
}
if (fs::is_directory(x)) {
pout(x);
}
}
*/

printf("hello\n");

Out(1111);

return 0;
}
  1. decltype(v) //返回v的数据类型 v可以是基础类型指针 函数指针 函数 …

  2. std::result_of<>//返回可调用类型的返回值

    1
    2
    3
    4
    5
    using TIF = std::function<int()>;

    TIF tif = []() -> int{};

    typedef std::result_of<TIF()>::type TA; //参数是类型 跟decltype类似
  3. std::future<数据类型> 对数据的封装

  4. std::async<>//同步调用线程

    1
    2
    3
    4
    5
    6
    7
    std::future<int> fut = std::async([]()->int{
    std::cout<<"async"<<std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 111;
    });

    std::cout<<"async return:"<<fut.get()<<std::endl;
  5. std::promise<数据类型>//对值得封装 //主要用于并发中的数据传递

    1
    2
    3
    4
    5
    6
    7
    8
    9
    std::promise<int> pro;
    std::future<int> f = pro.get_future();

    std::thread th8([](std::future<int>&f){
    std::cout<<"get future value:"<<f.get()<<std::endl;

    },std::ref(f));

    pro.set_value(999);
  6. std::packaged_task<函数>//对方法得封装 //主要用于并发中的方法 多线程中如果不把task放到多线程中会阻塞。

    1
    多线程中传递方法
  7. c++11后使用operator””自定义类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class OperatorTest11{
    public:
    OperatorTest11(){}
    std::string GetName(){return "Func Jay";}

    };

    // 参数是固定的, 不能少
    inline OperatorTest11 operator""_jay(const char * name,size_t n) {
    return OperatorTest11();
    }

    main() {
    auto opt_fun = "name"_jay;
    std::cout<<"Name"<<opt_fun.GetName()<<std::endl;
    }
c++ 惯用手法

New

std::chrono::time_point

std::reference_wrapper

compare_exchange_weak
compare_exchange_strong

std::this_thread::yield();

std::underlying_type();

attribute((aligned(64)));

template <typename… Targs> 多种类型构造封装

CAS机制:
CAS的基本思想是认为当前环境中的并发并没有那么高,比较乐观的看待整个并发,只需要在更新某个值时先检查下该值有没有发生变化,如果没有发生变化则更新,否则放弃更新。
CAS(compare and wasp)比较并操作,解决多线程并行情况下使用锁造成性能损耗的机制

RAII:
获取资源即初始化。将资源于对象绑定(构造函数获取资源,析构函数释放资源,资源)
RAII的本质内容是用对象代表资源,把管理资源的任务转化为管理对象的任务,将资源的获取和释放与对象的构造和析构对应起来,从而确保在对象的生存期内资源始终有效,对象销毁时资源必被释放。换句话说,拥有对象就等于拥有资源,对象存在则资源必定存在。由此可见,RAII惯用法是进行资源管理的有力武器。

常用封装 RAII expeted&error all_calss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#include <iostream>
#include <functional>
#include <fstream>
#include <mutex>


/*RAII use
1. 创建一个资源包装类
2. 在构造函数中获取资源(可选)
3. 在析构函数中释放资源
4. 在栈上创建资源包装类对象
*/
// like gurad_lock
class scoped_lock
{
public:
explicit scoped_lock(std::mutex& m)
: _m(m)
{
_m.lock();
}
~scoped_lock(void)
{
_m.unlock();
}
private:
std::mutex& _m;
};

void eg3(void)
{
std::mutex m;
scoped_lock locker(m);
// 使用资源
}

/*RAII

*/
class RAII{
public:
using InitFunc = std::function<void()>;
using ReleaseFunc = std::function<void()>;
RAII(const InitFunc &init_func,const ReleaseFunc &relese_func) : _release_func(relese_func) {
if(init_func) {
init_func();
}
}

explicit RAII(InitFunc & init_func){

}

~RAII(){
if(_release_func) {
_release_func();
}
}

private:
ReleaseFunc _release_func;
};

class User{
public:
explicit User(const std::string&name) : _name(name){
std::cout<<"name:"<<name<<std::endl;
}
User (const std::string&name,const std::string &sex) {
std::cout<<"name:"<<name<<std::endl;
std::cout<<"sex:"<<sex<<std::endl;
}

std::string&& GetName(){
std::cout<<"Name:"<<_name<<std::endl;
return std::move(_name);
}
private:
std::string _name;
}; //RAII

// error code
enum class UserErrorType: int8_t {
UserA = 0x01,
UserB = 0x02,
UserC = 0x03
};


template<typename T = void>
struct Success{
Success(){}
};

template <>
struct Success<void>
{

};

template<typename T>
struct Error{
Error(const T & error_code) : _t(error_code) { // attention const(must)
}
T _t;
};

// return class wapper. we use it like error code system
template<typename T>
class Expected{
public:
Expected(T &t) : _t(t){}

Expected(Success<T> &s) : _has_error(false){}
Expected(Success<T> &&s) : _has_error(false){}

Expected(const Success<void> &s) : _has_error(false){}
// Expected(Success<void> &&s) : _has_error(false){}


Expected(Error<T>&e) : _has_error(true),_t(e){}
Expected(Error<T>&&e) : _has_error(true),_t(e){}

~Expected(){}

int32_t value(){
return _t.value();
}

private:
T _t; //error code
bool _has_error; //status

};

// class construct wapper
template <typename T>
class AllClass{
public:
AllClass(){}

template<typename...Args>
void AllClassArgs(Args &...args);

~AllClass(){}

private:

};

template<typename T>
template<typename... Args>
void AllClass<T>::AllClassArgs(Args & ...args) {
std::cout<<"AllClassArgs Construct"<<std::endl;
T t(std::forward<Args>(args)...);
};

//main
int main(int argc,char **argv) {
//RAII wapper
User *user = nullptr;
RAII raii([&user]{if(!user){user = new User("FuckYou");}},[&user]{delete user;});//分配在栈上,init_func和release_func保证资源得到初始化和释放。
std::cout<<user->GetName()<<std::endl;

// 手动分配空间
uint8_t tuser[sizeof(User)];

// User * tuser = nullptr;
new (static_cast<User*>(static_cast<void*>(tuser))) User("SB");
std::cout<<"tuser:"<<(static_cast<User*>(static_cast<void*>(tuser))->GetName())<<std::endl;

// multi-class return wapper
User tu("A");
Expected<User> error = tu;

Expected<UserErrorType> error_a = Error<UserErrorType>(UserErrorType::UserA);

Expected<int> succ = Success<int>();
Expected<int> succi = Success<>(); // attention template has default value T = void

//multi-classs construct wapper
AllClass<User> all_class;
all_class.AllClassArgs("Jay","Man");

all_class.AllClassArgs("Jay");



return 0;
}


int main(int argc,char **argv) {

User *user = nullptr;
RAII raii([&user]{if(!user){user = new User("FuckYou");}},[&user]{delete user;});
std::cout<<user->GetName()<<std::endl;


uint8_t tuser[sizeof(User)];
new (static_cast<User*>(static_cast<void*>(tuser))) User("SB");
std::cout<<"tuser:"<<(static_cast<User*>(static_cast<void*>(tuser))->GetName())<<std::endl;


AllClass<User> all_class;
all_class.AllClassArgs("Jay","Man");

all_class.AllClassArgs("Jay");

c++11 future

1
2
3
4
5
6
1. enable_shared_from_this

sigfillset
pthread_sigmask

boost::property_tree::ptree
Donate comment here.
Jay 微信

微信