C++ 14新增特性以及代码示例
目录
1. 泛型Lambda(Generic Lambdas)
2. 返回类型推导(Return Type Deduction)
3. 变量模板(Variable Templates)
4. 放宽constexpr限制
5. 二进制字面量(Binary Literals)
支持0b前缀表示二进制数
6. Lambda初始化捕获(Lambda Capture Initializers)
7. std::make_unique
8. 数字分隔符(Digit Separators)
9. [[deprecated]]属性
10. 扩展的constexpr标准库支持
1. 泛型Lambda(Generic Lambdas)
Lambda表达式支持auto参数,实现类似模板的泛型操作
auto print = [](const auto& x) { std::cout << x << "\n"; };
print(42); // 输出 int
print("Hello"); // 输出 const char*
2. 返回类型推导(Return Type Deduction)
函数返回类型可通过auto自动推导,支持decltype(auto)保留引用语义
auto add(int a, int b) { return a + b; } // 返回 intint x = 42;
decltype(auto) getRef() { return x; } // 返回 int&
decltype(auto) getValue() { return x; } // 返回 int
3. 变量模板(Variable Templates)
支持定义模板化的全局变量,简化元编程
template<typename T>
constexpr T pi = T(3.1415926535897932385);double area = pi<double> * radius * radius; // 使用 double 类型 pi
4. 放宽constexpr限制
允许在constexpr函数中使用局部变量、循环和条件语句
constexpr int factorial(int n) {if (n <= 1) return 1;int result = 1;for (int i = 2; i <= n; ++i) result *= i;return result;
}
static_assert(factorial(5) == 120, "Error");
5. 二进制字面量(Binary Literals)
支持0b前缀表示二进制数
int flags = 0b1010; // 十进制 10
6. Lambda初始化捕获(Lambda Capture Initializers)
捕获列表支持直接初始化变量
int x = 10;
auto lambda = :ml-search[value = x + 1] { return value; }; // 捕获 value = 11
7. std::make_unique
新增智能指针工厂函数,简化unique_ptr创建
auto ptr = std::make_unique<int>(42); // 替代 new int(42)
8. 数字分隔符(Digit Separators)
允许在数字中使用单引号(')分隔,提升可读性
int million = 1'000'000; // 等效于 1000000
9. [[deprecated]]属性
标记废弃的代码,编译时生成警告
[[deprecated("Use newFunc() instead")]]
void oldFunc() {}
10. 扩展的constexpr标准库支持
部分标准库函数(如std::array)支持constexpr
constexpr std::array<int, 3> arr = {1, 2, 3};
static_assert(arr[1] == 2, "Error");
以上特性均基于C++14对C++11的增量改进,注重实用性和代码简洁性