这是一个通用的“StrongType”模板,我们用它来包装不同的类型和上下文。这个答案的唯一显着区别 是我们更喜欢使用一个标签类型,它为每个专门的包装器类型提供一个有意义的名称:
template <typename ValueType, class Tag> class StrongType {
public:
inline StrongType() : m_value(){}
inline explicit StrongType(ValueType const &val) : m_value(val) {}
inline operator ValueType () const {return m_value; }
inline StrongType & operator=(StrongType const &newVal) {
m_value = newVal.m_value;
return *this;
}
private:
//
// data
ValueType m_value;
};
以及模板的使用如下:
class ArrayIndexTag;
typedef StringType<int, ArrayIndexTag> StrongArrayIndex;
StringArrayIndex arrayIndex;
还要注意,所有函数都是“内联”的,其目的是编译器可以尽最大努力生成与完全不使用模板时生成的代码完全相同的代码!