C++14/17新特性

C++14:

  • auto优化
    函数返回值可以为auto类型
 auto func(int index)
 {
	return index;
 }

lambda参数可以为auto

auto f = [] (auto a) { return a; };
  • std::make_unique
    C++11中对智能指针只有std::make_shared,C++14中添加std::make_unique。示例:
class Test {};
std::unique_ptr<Test > ptr = std::make_unique<Test >();
  • std::quoted
 给字符串添加双引号。示例:
 int main() {
    string str = "My Test";
    cout << str << endl;
    cout << std::quoted(str) << endl;
    return 0;
}
输出:
My Test
"My Test"

C++17:

  • 构造函数模板推导
    vector v = {1, 2, 3}; // c++17
  • if-switch语句初始化
if (int a = 100 ; a < 101) {
   cout << a;
}
  • 结构化绑定
    可以绑定tuple、pair、map以及结构体和数组。示例:
    //结构体
struct Pos{
   int x;
   int y;
};
Pos funcStruct() {
   return {0, 0};
}
//tuple
 std::tuple<int, std::string> funcTuple() {
   return std::tuple(1, "hello world!");
}
//pair
 std::pair <int, double> funcPair() {
   return std::pair (1, 1.1);
}
//map
 std::map<int, string> m = {
    {0, "A"},
    {1, "B"},  
  };
int main() {
	//tuple绑定
   auto [i, str] = funcTuple();
   //pair绑定
   auto[i, f] = funcPair();
   //结构体绑定
   const auto [x, y] = funcStruct();
   //map绑定
   for (const auto &[i, s] : m) {
       cout << i << " " << s << endl;
  }
  //数组绑定
  int array[3] = {1, 2, 3};
  auto [a, b, c] = array;
}
  • 内联变量
    C++17之前之后内联函数,现在新增了内联变量,C++类的静态成员变量不允许在头文件中初始化,但是内联变量却可以。
class Test {
publicinline static const int value = 0;
}
  • 折叠表达式
    新增折叠表达式可以使可变参数模板编程更加方便:
template <typename ... Ts>
auto sum(Ts ... Tn) {
   return (Tn + ...);
}
int a {sum(1, 2, 3, 4, 5)}; // 15
std::string A{"hello "};
std::string B{"world"};
cout << sum(A, B) << endl; // hello world
  • file_system
    包含了对文件的基本操作
std::filesystem::create_directory(fileDir);//创建文件夹
std::filesystem::copy(fromPath,toPath);//复制文件或者目录
std::filesystem::copy_file(src, dst, std::filesystem::copy_options::skip_existing);
std::filesystem::exists(fileName);//判断文件是否存在
std::filesystem::current_path(errCode);//当前路径
std::filesystem::remove(fileDir)//清空文件夹
std::filesystem::rename(oldFileName,newFileName)//重命名
  • as_const
    用于将左值转成const类型变量
std::string str = "hello world";
const std::string& strTest = std::as_const(str);
  • std::optional
    在开发中我们可能会处理返回空变量的情况,std::optional可以解决此问题
 std::optional<std::string> Test::getName()
{
	std::string str = "my name";
	if (!str.empty())
	{
		return str ;
	}
	return std::nullopt;
}
// 使用
Test test;
std::optional<std::string> strName = test.getName();
if (strName )
{
	cout << strName  <<endl
}
  • namespace嵌套
//C++17 before
namespace A {
   namespace B {
       namespace C {
           void func();
      }
  }
}
// C++17
namespace A::B::C {
   void func();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值