2

In C++ I want to create a typed variable that won't accidentally be used or converted to some other type. What I've come up with is:

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

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

This seems to work, though sometimes I need to directly access the value, but are there any other methods I really should define? Does it use any extra resources at run time? (I could use preprocesser commands to switch it out with a "using TId = uint32_t" if not in debug mode, though that would mean extra work whenever I need to directly access the value.)

Or is there some better approach that I just haven't noticed?

Jason
  • 36,170
  • 5
  • 26
  • 60

1 Answers1

0

You may make the structure templated so that it can be used at multiple places and define a typecast operator.

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>;

Your code as it is also fine. Above way is for better utilization and avoid repetition.

Vishakha
  • 36
  • 3