2013-02-21 48 views
8

C++中是否存在严格typedef的习惯用法,可能使用模板?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; 

所以我可以做这样的一个编译时错误:

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

x = y; // whoops 

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

+1

坐标是不是这是一个非常好的应用。两个坐标的乘积不是坐标等。您可能想要查看Boost.Units。 – 2013-02-21 15:40:06

+2

我删除了我的答案,其中提示[BOOST_STRONG_TYPEDEF](http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/strong_typedef.html),因为它显然适用于重载分辨率,但不会生成编译错误交叉分配。 – Angew 2013-02-21 15:42:24

+0

我质疑你想做什么的价值。例如,当你想要执行旋转时会发生什么? 'x = sin(theta)* y + cos(theta)* x'应该是完全有效的。 – 2013-02-21 16:46:38

回答

5

我在我的项目中使用了类似的东西。只有我使用类型标记而不是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 
+0

我认为用简单的“#define new_type(base,tag)typedef new_type <## base,class TAG _ ## tag> tag; – slacy 2013-03-13 23:55:04

+1

@slacy dunno,我觉得宏很丑,并避免它们 – 2013-03-14 11:25:03

2

不可以。有建议让它进入下一个标准(C++ 14或C++ 17),但不适用于C++ 11。

+1

-1:他没有问是否使用语言,并且有方法可以在“用户空间”。因此,这个答案是不正确的。 – 2013-02-21 15:26:23

+0

在用户空间中没有办法与提议的语言特征相同。 – Puppy 2013-02-21 18:34:06

+0

这与问题中陈述的内容相同吗?既然Angew的答案已经失效了,我很乐意接受这个可能性,但是需要你的输入。 – 2013-02-21 20:00:54

0

用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()); 
} 

输出:

x1 
x2 
y1 
y2 
i1 
i2 

编译器:

的Visual Studio 2015年,GCC 4.8.x