gpt4 book ai didi

c++ - 如何在实例化我的模板类时避免使用宏?

转载 作者:行者123 更新时间:2023-12-03 06:54:57 24 4
gpt4 key购买 nike

我们使用了大量的寄存器,都是位域结构,例如

struct MyRegister { 
uint32_t bit_field0 : 2;
uint32_t bit_field1 : 5;
...
};
volatile MyRegister my_register; // Mapped by the linker to a specific address.

我想创建一个模板来帮助我创建影子寄存器。像这样的东西:

Shadow<> my_register_shadow(my_register); // my_register_shadow is a variable initialized with my_register address and value (reads my_register value).
my_register_shadow.bit_field0 = 2; // Doesn't access to real register my_register.
my_register_shadow.bit_field1 = 6; // Doesn't access to real register my_register.
my_register_shadow.flush(); // Only now write to my_register.

我目前的解决方案:

template <typename T>
class Shadow : public T
{
public:
Shadow(volatile T& reg) : T(reg), reg_(reg) {}
void flush() { reg_ = *this; }
private:
volatile T& reg_;
};

#define SHADOW_REG(SHADOW, REG) Shadow<decltype(REG)> SHADOW(REG)
SHADOW_REG(my_register, my_register_shadow); // Define my_register_shadow variable.
my_register_shadow.bit_field0 = 2; // Doesn't access to real register my_register.
my_register_shadow.bit_field1 = 6; // Doesn't access to real register my_register.
my_register_shadow.flush(); // Only now write to my_register.

我正在寻找一个没有宏的解决方案,有什么想法吗?

最佳答案

一个简单的模板化工厂将满足您的需求:

template <typename T>
Shadow<T> createShadow(T& reg) { return {reg}; }

auto my_register_shadow = createShadow(my_register); // Define my_register_shadow variable.
my_register_shadow.bit_field0 = 2; // Doesn't access to real register my_register.
my_register_shadow.bit_field1 = 6; // Doesn't access to real register my_register.
my_register_shadow.flush(); // Only now write to my_register.

关于c++ - 如何在实例化我的模板类时避免使用宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64022604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com