函数返回值类型推导用于模板
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> template<typename T> auto func(T t) { return t; } int main() { std::cout << func(4) << std::endl; std::cout << func(3.4) << std::endl; return 0; } |
变量模板
1 2 3 4 5 6 7 8 |
template<class T> constexpr T pi = T(3.1415926231312); int main() { std::cout << pi<int> << std::endl; std;:cout << pi<double> << std::endl; return 0; } |
别名模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
template<typename T, typename U> struct A { T t; U u; }; template<typename T> using B = A<T, int>; int main() { B<double> b; b.t = 10; b.u = 20; cout << b.t << endl; cout << b.u << endl; return 0; } |
std::shared_timed_mutex与std::shared_lock
- C++14通过std::shared_timed_mutex和std::shared_lock来实现读写锁,保证多个线程可以同时读,但是写线程必须独立运行,写操作不可以同时和读操作一起进行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
struct ThreadSafe { mutable std::shared_timed_mutex mutex_; int value_; ThreadSafe() { value_ = 0; } int get() const { std::shared_lock<std::shared_timed_mutex> loc(mutex_); return value_; } void increase() { std::unique_lock<std::shared_timed_mutex> lock(mutex_); value_ += 1; } }; |
std::integer_sequence
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
template<typename T, T... ints> void print_sequence(std::integer_sequence<T, ints...> int_seq) { std::cout << "The sequence of size " << int_seq.size() << ": "; ((std::cout << ints << ' '), ...); std::cout << '\n'; } int main() { print_sequence(std::integer_sequence<int, 9, 2, 5, 1, 9, 1, 6>{}); return 0; } 输出:7 9 2 5 1 9 1 6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
template <std::size_t... Is, typename F, typename T> auto map_filter_tuple(F f, T& t) { return std::make_tuple(f(std::get<Is>(t))...); } template <std::size_t... Is, typename F, typename T> auto map_filter_tuple(std::index_sequence<Is...>, F f, T& t) { return std::make_tuple(f(std::get<Is>(t))...); } template <typename S, typename F, typename T> auto map_filter_tuple(F&& f, T& t) { return map_filter_tuple(S{}, std::forward<F>(f), t); } |
std::exchange
1 2 3 4 5 6 |
template<class T, class U = T> constexpr T exchange(T& obj, U&& new_value) { T old_value = std::move(obj); obj = std::forward<U>(new_value); return old_value; } |
1 2 3 4 5 6 7 8 9 |
int main() { std::vector<int> v; std::exchange(v, {1,2,3,4}); cout << v.size() << endl; for (int a : v) { cout << a << " "; } return 0; } |
std::quoted
- 添加引号
1 2 3 4 5 6 |
int main() { string str = "hello world"; cout << str << endl; cout << std::quoted(str) << endl; return 0; } |
本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 51CTO:C++语言高级课程一08/07
- ♥ Soui七06/02
- ♥ Deelx正则引擎使用12/24
- ♥ Boost 程序库完全开发指南:工具与字符串08/22
- ♥ C++11_第四篇12/08
- ♥ 51CTO:C++语言高级课程三08/15