65.9K
CodeProject 正在变化。 阅读更多。
Home

自动值

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.92/5 (6投票s)

2004年2月28日

BSD

1分钟阅读

viewsIcon

50121

Auto Value 是具有未定义状态的变量的实现。

引言

在编程中,有时需要表示具有“未定义”或“未知”值的变量。

假设你有一些对象或结构,它们被持久化到 XML 文件中。在读取 XML 时,某些字段可能会被省略,你需要以某种方式处理这种情况。反之,在将类序列化到 XML 时,最好不要输出未知值,只是为了减少冗余。

下面的模板是我尝试将问题泛化的结果。至少对我自己而言。希望它也能帮助到其他人。

要定义这样一个自动值,你需要提供基本类型(T)、一些默认值(T default_value) 并选择一个 T null_value ,它将代表未定义的状态。

示例 1 - 具有 TRUEFALSE 和未定义状态的“三态”值

typedef t_value<BOOL,0,0xFF> tristate_v;

示例 2 - 工资值

typedef t_value<DWORD,0,0xFFFFFFFF> salary_v;

现在我们可以像这样声明我们的业务对象:

struct employee 
{ 
tristate_v is_married;
salary_v   salary;
};

value_t 的一个显而易见的优势是,它在内存中占用的空间与基本类型一样多,并且其值默认初始化。因此,你不需要为你的结构编写很长的初始化器列表。

实现

实现非常简单明了,我认为没有人需要对其进行任何注释。

template<typename T, T default_value, T null_value >
  struct t_value
  {
    T _v;  
    t_value(): _v(null_value) {}
    t_value(const T& iv): _v(iv) {}
    t_value(const t_value& c): _v(c._v) {} 
    
    operator T() const { return _v == null_value? default_value: _v; }
    t_value& operator = (T nv) { _v = nv; return *this; }
 
    static T null_val() { return null_value; } 
 
    bool undefined() const { return _v == null_value; }
    bool defined() const { return _v != null_value; } 
 
    void clear()      { _v = null_value; } 
 
    /* Idea of val methods - handmade inheritance. */
    static T       val(const t_value& v1,T defval) 
        { return v1.defined()? v1._v:defval; } 
    static t_value val(const t_value& v1,const t_value& v2)
    {
      if(v1.defined()) return v1;
      return v2;
    }
    static t_value val(const t_value& v1,const t_value& v2, 
        const t_value& v3)
    {
      if(v1.defined()) return v1;
      if(v2.defined()) return v2;
      return v3;
    }
    static T val(const t_value& v1,const t_value& v2,T defval)
    {
      t_value tv = val(v1,v2);
      return tv.defined()? tv._v: defval;
    }
    static T val(const t_value& v1,const t_value& v2, 
        const t_value& v3,T defval)
    {
      t_value tv = val(v1,v2,v3);
      return tv.defined()? tv._v: defval;
    }
  };

当然,我正在使用这个模板来存储我的 HTMEngine 中的 HTML 属性:)

© . All rights reserved.