使用struct的C++类型化变量

C++ typed variables using struct

本文关键字:类型化 变量 C++ struct 使用      更新时间:2024-05-24

在C++中,我想创建一个类型化变量,它不会被意外使用或转换为其他类型。我想到的是:

struct  DId {
uint32_t    v;  
DId (uint32_t i = 0)    
{   
v   =   i;  
}
};
struct  TId {   
uint32_t    v;  
TId (uint32_t i = 0)    
{   
v   =   i;  
}
};

这似乎很有效,尽管有时我需要直接访问值,但我真的应该定义其他方法吗?它在运行时是否使用任何额外的资源?(如果不是在调试模式下,我可以使用预处理器命令用"使用TId=uint32_t"来切换它,尽管这意味着每当我需要直接访问值时都需要额外的工作。(

还是有一些我还没有注意到的更好的方法?

您可以将结构模板化,以便它可以在多个位置使用,并定义类型转换运算符。

template<typename T>
struct Id {
T v;  
Id (T i = T{}) { v = i; }. // Ideally not required
operator T () { return v; } // optional to allow conversion to T
};
using DId = Id<uint32_t>;

你的代码也很好。以上方式是为了更好地利用和避免重复。