zou*_*nds 9 c++ templates types idioms
在C++中是否存在严格typedef的习惯用法,可能使用模板?
就像是:
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;
Run Code Online (Sandbox Code Playgroud)
所以我可以做这样的编译时错误:
x_coordinate x(5);
y_coordinate y(6);
x = y; // whoops
Run Code Online (Sandbox Code Playgroud)
将__LINE__在那里看起来可能很麻烦,但我不希望手动创建一组常量仅仅保留每个类型是独一无二的.
小智 7
我在我的项目中使用类似的东西.只有我使用类型标记而不是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;
Run Code Online (Sandbox Code Playgroud)
请注意,TAG_*类不需要在任何地方定义,它们只是标记
x_coordinate x (1);
y_coordinate y (2);
x = y; // error
Run Code Online (Sandbox Code Playgroud)