chrome源码中的奇淫技巧

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

未完待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ปรัชญา แค้วคำมูล

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值