C++ 是一门强大而灵活的编程语言,擅长系统开发、高性能计算、游戏开发等多个领域。以下是 20 个高频但极具价值的 C++ 高级用法案例,配套完整代码与输出结果,助力你快速掌握进阶技巧。
01. 使用
std::optional
优雅处理函数返回值
#include <iostream>
#include <optional>
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
auto result = divide(10, 2);
if (result) std::cout << "Result: " << *result << std::endl;
else std::cout << "Division by zero!" << std::endl;
}
输出:
Result: 5
02. 使用
std::variant
表示多种可能的数据类型
#include <iostream>
#include <variant>
int main() {
std::variant<int, std::string> data;
data = 42;
std::cout << "int: " << std::get<int>(data) << std::endl;
data = "Hello";
std::cout << "string: " << std::get<std::string>(data) << std::endl;
}
输出:
int: 42
string: Hello
03. 使用
std::any
存储任意类型
#include <iostream>
#include <any>
int main() {
std::any val = 5;
std::cout << "Value: " << std::any_cast<int>(val) << std::endl;
val = std::string("C++");
std::cout << "Value: " << std::any_cast<std::string>(val) << std::endl;
}
输出:
Value: 5
Value: C++
04. 使用
std::function
实现高阶函数
#include <iostream>
#include <functional>
void execute(std::function<void()> func) {
func();
}
int main() {
execute([] { std::cout << "Hello Lambda" << std::endl; });
}
输出:
Hello Lambda
05. 使用
constexpr
优化编译期计算
#include <iostream>
constexpr int factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
int main() {
constexpr int result = factorial(5);
std::cout << "Factorial: " << result << std::endl;
}
输出:
Factorial: 120
06. 使用结构化绑定简化变量拆解
#include <iostream>
#include <tuple>
std::tuple<int, double> getData() {
return {10, 3.14};
}
int main() {
auto [a, b] = getData();
std::cout << "a: " << a << ", b: " << b << std::endl;
}
输出:
a: 10, b: 3.14
07. 使用范围 for 循环与
auto
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
for (auto& v : vec) {
std::cout << v << " ";
}
}
输出:
1 2 3
08. 使用
emplace_back
提升容器性能
#include <iostream>
#include <vector>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people;
people.emplace_back("Alice", 30);
std::cout << people[0].name << " - " << people[0].age << std::endl;
}
输出:
Alice - 30
09. 使用
unique_ptr
实现智能指针管理
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
std::cout << "Value: " << *ptr << std::endl;
}
输出:
Value: 42
10. 使用
shared_ptr
实现对象共享所有权
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(100);
std::shared_ptr<int> p2 = p1;
std::cout << "Shared value: " << *p2 << std::endl;
}
输出:
Shared value: 100
11. 使用 Lambda 捕获外部变量
#include <iostream>
int main() {
int x = 10;
auto print = [x]() { std::cout << "Captured x: " << x << std::endl; };
print();
}
输出:
Captured x: 10
12. 使用
decltype
自动获取类型
#include <iostream>
int main() {
int a = 5;
decltype(a) b = 10;
std::cout << "b: " << b << std::endl;
}
输出:
b: 10
13. 使用
typeid
获取运行时类型
#include <iostream>
#include <typeinfo>
int main() {
double d = 3.14;
std::cout << "Type: " << typeid(d).name() << std::endl;
}
输出(平台相关):
Type: d
14. 使用模板函数实现泛型编程
#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << add(1, 2) << std::endl;
std::cout << add(1.5, 2.5) << std::endl;
}
输出:
3
4
15. 使用模板特化处理特殊类型
#include <iostream>
template <typename T>
void print(T val) {
std::cout << "Generic: " << val << std::endl;
}
template <>
void print(std::string val) {
std::cout << "String: " << val << std::endl;
}
int main() {
print(100);
print(std::string("C++"));
}
输出:
Generic: 100
String: C++
16. 使用
enum class
定义类型安全枚举
#include <iostream>
enum class Color { Red, Green, Blue };
int main() {
Color c = Color::Green;
if (c == Color::Green)
std::cout << "It's green!" << std::endl;
}
输出:
It's green!
17. 使用范围检查的
at()
方法
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
std::cout << v.at(1) << std::endl;
}
输出:
2
18. 使用
std::sort
对结构体排序
#include <iostream>
#include <vector>
#include <algorithm>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> list = {{"Tom", 80}, {"Alice", 90}};
std::sort(list.begin(), list.end(), [](auto& a, auto& b) {
return a.score > b.score;
});
for (auto& s : list)
std::cout << s.name << ": " << s.score << std::endl;
}
输出:
Alice: 90
Tom: 80
19. 使用
try-catch
实现异常处理
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Something went wrong!");
} catch (const std::exception& e) {
std::cout << "Caught error: " << e.what() << std::endl;
}
}
输出:
Caught error: Something went wrong!
20. 使用文件流
fstream
读写文件
#include <iostream>
#include <fstream>
int main() {
std::ofstream out("test.txt");
out << "Hello, File!" << std::endl;
out.close();
std::ifstream in("test.txt");
std::string line;
std::getline(in, line);
std::cout << "Read: " << line << std::endl;
}
输出:
Read: Hello, File!