Idiom for strict typedef in C++
c++, idioms, templates, types
Solution
I'm using something similar in my project. Only I use type tagging instead of int. Works well in my particular application.
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;
Note that TAG_* classes don't need to be defined anywhere, they are just tags
x_coordinate x (1);
y_coordinate y (2);
x = y; // error
Problem
Is there an idiom for a strict typedef in C++, possibly using templates? Something like: ``` 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; ``` So I can make something like this a compile time error: ``` x_coordinate x(5); y_coordinate y(6); x = y; // whoops ``` The `__LINE__` in there looks like it might be trouble, but I'd prefer not to have to manually create a set of constants merely to keep each type unique.