Idiom for strict typedef in C ++

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; 

Therefore, I can make something like a compile-time error:

 x_coordinate x(5); y_coordinate y(6); x = y; // whoops 

__LINE__ looks like this might be a problem, but I would prefer not to manually create a set of constants so that each type is unique.

+8
c ++ idioms types templates
source share
3 answers

I use something similar in my project. Only I use type tags instead of int. Works well in my specific 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 the TAG_ * classes should not be defined anywhere, these are just tags

 x_coordinate x (1); y_coordinate y (2); x = y; // error 
+5
source share

Not. There are suggestions for this to move on to the next standard (C ++ 14, or perhaps C ++ 17), but not in C ++ 11.

+2
source share

C ++ 11:

 #include <stdio.h> struct dummy {}; struct NotMineType { NotMineType(dummy) {} }; template <int N> struct type_scope { struct MyOwnType { }; struct ConvertedToMineType : NotMineType { template <typename ...Args> ConvertedToMineType(Args... args) : NotMineType(args...) {}; }; enum myint : int {}; }; typedef type_scope<0>::MyOwnType x1; typedef type_scope<1>::MyOwnType x2; typedef type_scope<0>::ConvertedToMineType y1; typedef type_scope<1>::ConvertedToMineType y2; typedef type_scope<0>::myint i1; typedef type_scope<1>::myint i2; void foo(x1) { printf("x1\n"); } void foo(x2) { printf("x2\n"); } void foo(y1) { printf("y1\n"); } void foo(y2) { printf("y2\n"); } void foo(i1) { printf("i1\n"); } void foo(i2) { printf("i2\n"); } int main() { foo(x1()); foo(x2()); foo(y1(dummy())); foo(y2(dummy())); foo(i1()); foo(i2()); } 

Output:

 x1 x2 y1 y2 i1 i2 

Compiled by:

Visual Studio 2015, GCC 4.8.x

0
source share

All Articles