📜  C++ 11 vs C++ 14 vs C++ 17(1)

📅  最后修改于: 2023-12-03 14:39:49.276000             🧑  作者: Mango

C++ 11 vs C++ 14 vs C++ 17

C++ is a widely used programming language that has evolved over the years with new features and improvements. In this article, we will compare the differences between C++ 11, C++ 14, and C++ 17, highlighting the new features introduced in each version.

C++ 11

C++ 11 introduced several important features that enhanced the language and made it more modern and expressive. Some of the key features are:

1. Auto Keyword
auto num = 10; // Compiler determines data type
2. Range-based for loop
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
    // Iterate over each element
}
3. nullptr
int* ptr = nullptr; // Null pointer initialization
4. Lambda expressions
auto sum = [](int a, int b) { return a + b; };
5. Smart pointers
std::unique_ptr<int> ptr(new int(10));
6. Type inference
std::vector<int> numbers = {1, 2, 3, 4, 5};
auto size = numbers.size(); // Compiler deduces the type
C++ 14

C++ 14 introduced several improvements over C++ 11 without significant language changes. Some notable features are:

1. Lambda capture expressions
int x = 5;
auto func = [value = x]() { return value; };
2. Variable templates
template<typename T>
constexpr T pi = T(3.1415926535897932385);
3. Binary literals
auto num = 0b1010; // Binary literal
4. Generic lambdas
auto lambda = [](auto x, auto y) { return x + y; };
5. constexpr if
template <typename T>
void process(T value) {
    if constexpr (std::is_integral_v<T>) {
        // Integer processing
    } else if constexpr (std::is_floating_point_v<T>) {
        // Float processing
    } else {
        // Other types
    }
}
C++ 17

C++ 17 introduced several new features and improvements to the language. Some notable features are:

1. Structured bindings
std::pair<int, std::string> data = {10, "hello"};
auto [num, str] = data; // Structured bindings
2. if constexpr in regular functions
template <typename T>
auto square(T value) {
    if constexpr (std::is_integral_v<T>) {
        return value * value;
    } else {
        return 0;
    }
}
3. Fold expressions
template<typename... Ts>
auto sum(Ts... args) {
    return (args + ...); // Fold expression
}
4. Inline variables
inline int num = 10; // Inline variable
5. New standard attributes
[[nodiscard]] int calculate();
6. Filesystem library
#include <filesystem>
namespace fs = std::filesystem;
fs::path filePath("/path/to/file.txt");

These are just a few selected features introduced in each version. C++ 11, C++ 14, and C++ 17 bring many more improvements and additions to the language, providing programmers with more expressive and efficient ways of writing code. It is important to keep up with the latest versions to leverage the power of C++ and improve development productivity.