强类型定义 [英] Strong typedefs

查看:32
本文介绍了强类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法制作一个类型的完整副本,以便在模板推导上下文中区分它们?举个例子:

#include 模板 结构测试{静态 int c(){静态整数 t = 0;返回 t++;}};typedef int 句柄;int main(){std::cout <<测试<int>::c()<<std::endl;std::cout <<测试<句柄>::c()<

由于 typedef 只为一个类型创建一个别名,这将打印 0, 1而不是所需的 0, 0.是否有任何解决方法?

解决方案

引用 cplusplus.com,

<块引用>

请注意,既不是 typedef 也不是 using 创建新的不同数据类型.它们只创建现有类型的同义词.这意味着类型上面的 myword 用 WORD 类型声明,也可以考虑输入无符号整数;这并不重要,因为两者实际上都是指的是同一类型.

由于inthandle 相同,输出0 1 是预期的.>

不过,正如@interjay 建议的那样,有一个解决方法.

您可以使用BOOST_STRONG_TYPEDEF.

BOOST_STRONG_TYPEDEF( int , handle );

Is there any way to make a complete copy of a type so that they can be distinguished in template deduction context? Take the example:

#include <iostream>

template <typename T>
struct test
{
    static int c()
    { 
        static int t = 0;
        return t++;
    }
};

typedef int handle;

int main()
{
    std::cout << test<int>::c() << std::endl;
    std::cout << test<handle>::c() << std::endl;
    return 0;
}

Since typedef only makes an alias for a type, this prints 0, 1 instead of the desired 0, 0. Is there any workaround for this?

解决方案

Quoting cplusplus.com,

Note that neither typedef nor using create new distinct data types. They only create synonyms of existing types. That means that the type of myword above, declared with type WORD, can as well be considered of type unsigned int; it does not really matter, since both are actually referring to the same type.

Since int and handle are one and the same, the output 0 1 is expected.

There's a workaround though, as @interjay suggests.

You can use BOOST_STRONG_TYPEDEF.

BOOST_STRONG_TYPEDEF( int , handle );

这篇关于强类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆