auto返回值推导
- 在C++14中,auto可以对返回值进行推导,而C++11中,需要后置返回值,例如:
auto func(int a, int b)
{
return a + b;
}
auto func(int a, int b) ->int
{
return a + b;
}
- 当多个return语句时,需要保证返回值为同一类型
泛型lambda
- C++14中,lambda支持对参数的类型推导,类似于模版,而C++11中需要指定参数类型,例如:
auto fn = [](auto a, auto b)
{
return a + b;
}
auto fn = [](int a, int b)
{
return a + b;
}
int a = 10;
auto fn = [a = a * 10]{ return a; }
变量模板
- C++14中新增了变量模板,需注意的是,变量模版仅支持基础数据类型的实体,例如:
template<typename T>
T a = T(100)
template<typename T>
T func(T b)
{
return a<T> * b;
}
func(10);
func(3.1415926);
constexpr函数
- C++14里对constexpr函数放松了条件,在C++11中
被修饰的函数必须有返回值,只能有一条单一的返回语句
constexpr int func(int a)
{
return a * 10;
}
constexpr int fucn(int a)
{
int b = 0;
for(int i = 0; i < a; ++i)
b *= i;
return b;
}
[[deprecated]]标记
- C++14中可以通过添加deprecated标记表示当前函数、类、结构体可能会被废弃,例如:
[[deprecated]]
void func() {}
class [[deprecated]] test {};
struct [[deprecated]] test {};
- 当需要添加提醒信息时,可在关键字后加入
[[deprecated("warning msg")]]
二进制字面量和数位分隔符
cout<< 0b1000'0000<<endl; // 128 cout << 0x0000'00FF << endl; // 255 cout << 3.14'15926<<endl; // 3.14159 cout << 100'000'000<<endl; // 100000000
新增标准库
std::make_unique
auto uniptr = std::make_unique<int>(1);
std::shared_timed_mutex & std::shared_lock & std::unique_lock
- C++14中通过std::shared_timed_mutex和std::shared_lock实现读写锁, 读std::shared_lock,写std::unique_lock
struct TestThread
{
mutable std::shared_timed_mutex mutex_;
int val;
TestThread()
{
val= 0;
}
int get() const
{
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
return val;
}
void increase()
{
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
val += 1;
}
};
std::integer_sequence
template<typename T, T... ints>
void cout_sequence(std::integer_sequence<T, ints...> int_seq)
{
std::cout << "The sequence of size " << int_seq.size() << ": ";
for(auto& i : {ints...})
{
cout << i;
}
std::cout << '\n';
}
int main()
{
cout_sequence(std::integer_sequence<int, 9, 2, 5, 1, 9, 1, 6>{});
cout_sequence(std::index_sequence<9, 2, 5, 1, 9, 1, 6>());
cout_sequence(std::make_integer_sequence<int, 7>());
cout_sequence(std::make_index_sequence<7>());
cout_sequence(std::index_sequence_for<int,char,int,float,double>());
return 0;
}
std::exchange
- 作用为将参数2的值给予参数1然后返回改变之前参数1的值,例如:
std::vector<int> vec1{1, 2, 3, 4};
std::vector<int> vec2{5, 6, 7, 8};
auto vec3 = std::exchange(vec1, vec2);
结果:vec1 = vec2 = {5, 6, 7, 8};
vec3 = {1, 2, 3, 4};
std::quoted
std::string str = "hello world";
std::cout << str << std::endl;
std::cout << std::quoted(str) << std::endl;
|