强类型 [英] Strong typedefs

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

问题描述

有没有办法做一个类型的完整副本,以便他们可以在模板扣除上下文中区分?例如:

 模板< typename T> 
static test
{
static int c()
{
static int t = 0;
return i ++;
}
};

typedef int handle;

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

由于typedef只为类型创建别名,所以输出0,1 $是否有任何解决方法?

解决方案

引用 cplusplus.com


请注意,既不typedef也不使用创建新的不同数据类型。
它们只创建现有类型的同义词。
这意味着上面的myword类型
,用WORD类型声明,也可以考虑
类型unsigned int;


由于 int 句柄同一个,输出 0 1

你可以使用

a href =http://www.boost.org/doc/libs/1_61_0/libs/serialization/doc/strong_typedef.html =nofollow> 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:

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

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天全站免登陆