问题描述
42 as unsigned int is well defined as42U。
unsigned int foo = 42U; //是啊!
如何写23,以便清楚它是一个unsigned short int ?
unsigned short bar = 23; // booh!不清楚!
该问题的含义更清楚:
模板< class T>
void doSomething(T){
std :: cout< 未知类型< std :: endl;
}
模板<>
void doSomething(unsigned int){
std :: cout< unsigned int< std :: endl;
}
模板<>
void doSomething(unsigned short){
std :: cout< 无符号短< std :: endl;
}
int main(int argc,char * argv [])
{
doSomething(42U);
doSomething((unsigned short)23); //没有其他选项比转换?
return EXIT_SUCCESS;
}
数字文字不能有短
或无符号short
类型。
当然,为了分配 bar
,文字的值会隐式转换为 unsigned short
。在您的第一个示例代码中,您可以使用转换来显式转换,但我认为很明显已经发生了什么转换。浇铸可能更糟,因为对于一些编译器,它将平缓任何警告,如果文字值在 unsigned short
的范围之外,则会发出。再次,如果您希望使用这样的值有一个很好的理由,那么平息警告是好的。
在您的例子中编辑,其中它恰好是一个模板函数而不是一个重载的函数,你有一个替代的转型: do_something< unsigned short>(23)
。使用重载函数,你仍然可以避免使用:
void(* f)(unsigned short)=& do_something ;
f(23);
...但我不建议。如果没有别的,这只有当 unsigned short
版本实际存在,而调用与cast执行通常的重载分辨率找到最兼容的版本可用。 >
42 as unsigned int is well defined as "42U".
unsigned int foo = 42U; // yeah!
How can I write "23" so that it is clear it is an unsigned short int?
unsigned short bar = 23; // booh! not clear!
EDIT so that the meaning of the question is more clear:
template <class T>
void doSomething(T) {
std::cout << "unknown type" << std::endl;
}
template<>
void doSomething(unsigned int) {
std::cout << "unsigned int" << std::endl;
}
template<>
void doSomething(unsigned short) {
std::cout << "unsigned short" << std::endl;
}
int main(int argc, char* argv[])
{
doSomething(42U);
doSomething((unsigned short)23); // no other option than a cast?
return EXIT_SUCCESS;
}
You can't. Numeric literals cannot have short
or unsigned short
type.
Of course in order to assign to bar
, the value of the literal is implicitly converted to unsigned short
. In your first sample code, you could make that conversion explicit with a cast, but I think it's pretty obvious already what conversion will take place. Casting is potentially worse, since with some compilers it will quell any warnings that would be issued if the literal value is outside the range of an unsigned short
. Then again, if you want to use such a value for a good reason, then quelling the warnings is good.
In the example in your edit, where it happens to be a template function rather than an overloaded function, you do have an alternative to a cast: do_something<unsigned short>(23)
. With an overloaded function, you could still avoid a cast with:
void (*f)(unsigned short) = &do_something;
f(23);
... but I don't advise it. If nothing else, this only works if the unsigned short
version actually exists, whereas a call with the cast performs the usual overload resolution to find the most compatible version available.
这篇关于如何写一个unsigned short int literal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!