C+17 新特性

#include <any>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

 using namespace std;

 struct Point {
     int x;
     int y;
 };

 Point func() {
     return {1, 2};
 }

 template <typename ... Ts>
 auto sum(Ts ... ts) {
     return (ts + ...);
 }

 int main()
 {
     // c++17 类型自动推导
     vector a = {1, 2, 3};


     // 结构化绑定, pair, array, struct
     pair b(1, 2.3f);
     auto&& [i, j] = b;
     i = 2;
     cout << b.first << endl; // 2

     int array[3] = {1, 2, 3};
     const auto& [x, y, z] = array;
     cout << x << " " << y << " " << z << endl;  // 1, 2, 3

     const auto& [m, n] = func();
     cout << m << " " << n << std::endl;  // 1, 2


     // if-switch语句初始化
     // if (init; condition)
//     int a = GetValue();
//     if (a < 101) {
//         cout << a;
//     }
     if (int a = 100; a < 101) {
         cout << a << std::endl;  // 100
     }

     string str = "Hi World";
     if (auto [pos, _] = pair(str.find("Hi"), str.size()); pos != string::npos) {
         std::cout << pos << std::endl;  // 0
     }


     // 折叠表达式
     any any_varibale {sum(1, 2, 3, 4, 5)};
     cout << any_varibale.type().name() << " " << std::any_cast<int>(any_varibale) << endl;  // 15

     std::string d{"hello "};
     std::string e{"world"};
     cout << sum(d, e) << endl;  // hello world


     // std::any
     any_varibale = 1;
     cout << any_varibale.type().name() << " " << std::any_cast<int>(any_varibale) << endl;
     any_varibale = 2.2f;
     cout << any_varibale.type().name() << " " << std::any_cast<float>(any_varibale) << endl;
     any_varibale = std::string("123");
     cout << any_varibale.type().name() << " " << std::any_cast<std::string>(any_varibale) << endl;
 }
// namespace 嵌套
namespace A {
    namespace B {
        namespace C {
            void func();
        }
    }
}

namespace A::B::C {
    void func();)
}


  // inline variable in Header file "example.h":
 #ifndef EXAMPLE_H
#define EXAMPLE_H
 
#include <atomic>
 
// function included in multiple source files must be inline
inline int sum(int a, int b)
{
    return a + b;
}
 
// variable with external linkage included in multiple source files must be inline
inline std::atomic<int> counter(0);
 
#endif


// as_const可以将左值转成const类型, 比如用于lambda参数


// std::optional

// std::from_chars, std::to_chars

C++17新特性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值