1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include <iostream>
#include <string>
// 多行宏定义
#define DECLARE_GETTER_SETTER(type, name) \
private: \
type m_##name; \
public: \
const type& Get##name() const { return m_##name; } \
void Set##name(const type& value) { m_##name = value; }
// 字符串化操作符 #
#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)
// 连接操作符 ##
#define CONCAT(a, b) a##b
// 可变参数宏
#define PRINT_ARGS(...) printf(__VA_ARGS__)
#define LOG_INFO(format, ...) printf("[INFO] " format "\n", ##__VA_ARGS__)
// 调试宏
#ifdef _DEBUG
#define ASSERT(condition, message) \
do { \
if (!(condition)) { \
std::cerr << "Assertion failed: " << #condition \
<< " in " << __FILE__ << " at line " << __LINE__ \
<< ": " << message << std::endl; \
std::abort(); \
} \
} while(0)
#else
#define ASSERT(condition, message) ((void)0)
#endif
class Example
{
DECLARE_GETTER_SETTER(std::string, Name)
DECLARE_GETTER_SETTER(int, Age)
public:
Example() : m_Name(""), m_Age(0) {}
};
int main()
{
// 使用生成的getter/setter
Example obj;
obj.SetName("Alice");
obj.SetAge(25);
std::cout << "Name: " << obj.GetName() << std::endl;
std::cout << "Age: " << obj.GetAge() << std::endl;
// 字符串化
std::cout << "Stringified: " << STRINGIFY(Hello World) << std::endl;
std::cout << "To string: " << TO_STRING(123) << std::endl;
// 连接
int CONCAT(var, 1) = 10;
int CONCAT(var, 2) = 20;
std::cout << "var1 = " << var1 << ", var2 = " << var2 << std::endl;
// 可变参数宏
LOG_INFO("User %s logged in with ID %d", "Alice", 1001);
LOG_INFO("System started");
// 断言(仅在Debug模式下有效)
int value = 5;
ASSERT(value > 0, "Value must be positive");
// ASSERT(value > 10, "This will fail"); // 取消注释会触发断言
return 0;
}
|