c++ - C++ 中严格类型定义的习语

标签 c++ templates types idioms

在 C++ 中是否有严格类型定义的习惯用法,可能使用模板?

类似于:

template <class base_type, int N> struct new_type{
    base_type p;
    explicit new_type(base_type i = base_type()) : p(i) {}
};

typedef new_type<int, __LINE__> x_coordinate;
typedef new_type<int, __LINE__> y_coordinate;

所以我可以让这样的事情成为编译时错误:

x_coordinate x(5);
y_coordinate y(6);

x = y; // whoops

那里的 __LINE__ 看起来可能很麻烦,但我宁愿不必手动创建一组常量来保持每种类型的唯一性。

最佳答案

我在我的项目中使用了类似的东西。只有我使用类型标记而不是 int。在我的特定应用程序中运行良好。

template <class base_type, class tag> class new_type{     
  public:   
    explicit new_type(base_type i = base_type()) : p(i) {}

    //
    // All sorts of constructors and overloaded operators
    // to make it behave like built-in type
    //

  private:
     base_type p;
};

typedef new_type<int, class TAG_x_coordinate> x_coordinate;
typedef new_type<int, class TAG_y_coordinate> y_coordinate;

请注意,TAG_* 类不需要在任何地方定义,它们只是标签

x_coordinate x (1);
y_coordinate y (2);

x = y; // error

关于c++ - C++ 中严格类型定义的习语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15005809/

相关文章:

Python,元组索引必须是整数,而不是元组?

c++ - 如何在 Linux 中编译 C++ 程序?

c++ - 为什么这个函数返回的值与我在内联时返回的值不同?

c++ - 在C++中初始化参数化类型的数组

java - 需要更好的模板语言

haskell - 为什么 `succ i` 在 `i::Num a => a` 处有效(而不是 `Enum a` )?

c++ - 如果从函数返回指向指针 COM 对象的指针,是否需要 AddRef()?

c++ - 使用四元数方向的第一人称相机中的夹紧间距

c++ - 使用聚合初始化器初始化类的模板(聚合类型)成员但没有额外的括号

python - 存储映射到字符串的整数以便键可以是 python 中的范围的最佳方法是什么?