在 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/