C++多次展开宏技巧
头文件实现
#include "macro.h"头文件
// #pragma once 注意
// 首先取消之前的定义
#undef SUPER_MACRO
// 第一次展开:定义枚举
#if defined(FIRST_TIME)
#undef FIRST_TIME // 使用后立即取消定义
#define SUPER_MACRO(label, type) \
enum IDs { \
label##__ID = 10 \
};
// 第二次展开:定义类
#elif defined(SECOND_TIME)
#undef SECOND_TIME // 使用后立即取消定义
#define SUPER_MACRO(label, type) \
class TestClass { \
public: \
enum {ID = label##__ID}; \
TestClass(type value) : _value(value) {} \
type _value; \
};
#endif
#include "use_macro.h"
// #pragma once 注意
#include "macro.h"
SUPER_MACRO(Test, int)
客户端使用
#pragma once
#include <vector>
#include <windows.h>
#include <iostream>
// First expansion - Generate enum
#define FIRST_TIME
#include "use_macro.h"
// Second expansion - Generate class
#define SECOND_TIME
#include "use_macro.h"
int main() {
TestClass t(5);
std::cout << TestClass::ID << std::endl;
std::cout << t._value << std::endl;
return 0;
}
右值调用(临时对象优化)
#if 1
#include <iostream>
#include <string>
class Dict {
public:
// 省略成员变量和其他成员函数
Dict& Set(const std::string& key, const std::string& value)& {
std::cout << "Called by lvalue: Set key=" << key << ", value=" << value << std::endl;
return *this;
}
Dict&& Set(const std::string& key, const std::string& value)&& {
std::cout << "Called by rvalue: Set key=" << key << ", value=" << value << std::endl;
return std::move(*this);
}
};
int main() {
Dict dict1;
// 左值调用
dict1.Set("name", "Alice");
// 右值调用
Dict().Set("age", "30");
return 0;
}
#endif