创建新的基本类型 [英] Creating a new primitive type

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

问题描述

有没有办法创建一个类型的基本类型之一(例如char),并可以隐式转换之间,但将在模板中解决不同,例如,下面的代码工作? / p>

Is there a way to create a new type that is like one of the basic types (eg char), and can be implcitly converted between, but will resolve diffrently in templates, such that for example, the following code works?

typedef char utf8;
template<typename T>void f(T c);
template<> void f<char>(char c)
{
    std::cout << "ascii " << c << std::endl;
}
template<> void f<utf8>(utf8 c)//error C2766: explicit specialization; 'void f<char>(char)' has already been defined
{
    std::cout << "utf8 " << c << std::endl;
}
int main()
{
    char c1 = 'x';
    utf8 c2 = 'g';
    f(c1);
    f(c2);
}

我认为可能是一个包含单个数据的类成员,如果是这样,什么是最干净的方式做,并将编译器能够优化它,如果它是一个原始。

I'm thinking that it may be possible with a class containing a single data member, if so what is the cleanest way to do it, and will compilers be able to optimise it as if it was a primitive.

编辑:我试过BOOST_STRONG_TYPEDEF,这似乎是为基本的东西工作,但是我怎么可以从新类型创建一个std :: basic_string?

I tried BOOST_STRONG_TYPEDEF, and that seems to work for basic things, but how can I then go onto create a std::basic_string from the new type?

BOOST_STRONG_TYPEDEF(char,utf8);
//first try
BOOST_STRONG_TYPEDEF(std::string,utf8_string);
//second try
typedef std::basic_string<utf8, std::char_traits<utf8>,std::allocator<utf8> > uft8_string;

第一个没有真正工作,因为结果类型仍然期望char的所有方法,第二个似乎不喜欢存在的构造函数和赋值运算符:(

The first one doesn't really work because the resulting type still expects char for all its methods, and the second one doesn't seem to like the presence of constructors and assignment operators :(

我没有尝试另一种方式来创建新的char类型,如果我不能用BOOST_STRONG_TYPEDEF?

I haven't tried the other way to create the new char type yet, will it be able to get around this if I cant with BOOST_STRONG_TYPEDEF?

推荐答案

我听说有传闻说C ++ 0x会带来强大typedefs将允许utf8类在你的情况下可以从char区分,但目前不存在。可能Boost的 strong typedef 会有帮助,但我不知道。

I heard a rumour that C++0x will bring strong typedefs which will allow for the utf8 class in your case to be distinguishable from the char, but that doesn't exist currently. Maybe Boost's strong typedef would help, but I don't know.

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

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