Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟีเจอร์ใหม่ของ C++17


คณะกรรมการมาตรฐาน C++ เปิดตัวฟีเจอร์ใหม่ทุก 3 ปี สองส่วนหลักคือ Core Language และ Standard Template Library (STL) ฟีเจอร์ใหม่เน้นโค้ดสะอาด กระชับ และง่ายขึ้น ดังนี้

1. Fold Expressions (นิพจน์การพับ)

ใช้เขียนโค้ดสั้นสำหรับจำนวนอาร์กิวเมนต์ไม่คงที่ ที่ส่งเข้าฟังก์ชันหรือคืนค่า รองรับ unary/binary left/right fold

Syntax:

  • Unary right fold: (pack op ...)
  • Unary left fold: (... op pack)
  • Binary left fold: (init op ... op pack)
  • Binary right fold: (pack op ... op init)

pack = parameter pack, op = operator (+, -, *, /, ==, <=, ...), init = ค่าเริ่มต้น

ตัวอย่าง:

#include <iostream>
#include <string>
using namespace std;

template<typename ...Args>
auto addition(Args ...args) {
    return (args + ... + 0);
}

template<typename ...Args>
auto sum2(Args ...args) {
    return (args + ...);
}

int main() {
    cout << "Sum is: " << addition(1,1,1,1,1) << endl;
    cout << "Sum 2 is: " << addition(1,2,3);
}
Sum is: 5
Sum 2 is: 6

2. Structured Bindings (การผูกโครงสร้าง)

ประกาศหลายตัวแปรกับค่าเริ่มต้นจาก pair, tuple, array ในคำสั่งเดียว

กรณีที่ 1: ผูกอาร์เรย์

int arry[3] = {3,4,5};
auto [a,b,c] = arry; // a=3, b=4, c=5

กรณีที่ 2: ผูก tuple-like

float fnum{};
char ch1{};
int number{};
std::tuple<float&, char&&, int> tplex(fnum, std::move(ch1), number);
const auto& [p, q, r] = tplex;

กรณีที่ 3: ผูก data members

struct structVar {
    mutable int num1 : 2;
    volatile double num2;
};
structVar func();
const auto [a, b] = func();

3. การ Initialize Enum ด้วย Direct List

C++17 ให้ใช้ braces เริ่มต้น enum ได้

enum byte : unsigned char {};
byte b0{0};       // OK
byte b1 = byte{1}; // OK
byte b2 = byte{256}; // ERROR (0-255 only)

4. การประกาศตัวแปรใน If และ Switch

ประกาศตัวแปรในเงื่อนไข if/switch ได้ ทำให้ใช้ชื่อซ้ำใน scope ต่างๆ ได้

if (data_type variable condition) { ... }
switch (condition; variable) { ... }

5. If constexpr Statement

ประเมินที่ compile-time เหมาะกับ template code

If-else ธรรมดา (runtime):

int var = 10;
if (var >= 10) { var += 10; } else { var -= 10; }

Constexpr If-else (compile-time):

template <typename T>
auto length(T const& value) {
    if constexpr (is_integral<T>::value) {
        return value;
    } else {
        return value.length();
    }
}

6. Nested Namespaces (เนมสเปซซ้อน)

Syntax ใหม่สะดวกกว่า ไม่ต้องเปิด/ปิด braces หลายชั้น

ก่อน C++17:

namespace Earth {
    namespace Continent {
        namespace Country {
            class City { ... };
        }
    }
}

C++17:

namespace Earth::Continent::Country {
    class City { ... };
}