c++ - 如何写一个无符号的短整型文字?

标签 c++ types

42 as unsigned int 很好地定义为“42U”。

unsigned int foo = 42U; // yeah!

我怎样才能写出“23”,以便清楚它是一个无符号短整型?

unsigned short bar = 23; // booh! not 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;
}

最佳答案

你不能。数字文字不能有 shortunsigned short输入。

当然是为了分配给bar ,文字的值被隐式转换为 unsigned short .在您的第一个示例代码中,您可以通过强制转换显式地进行转换,但我认为很明显会发生什么转换。强制转换可能更糟,因为对于某些编译器,如果文字值超出 unsigned short 的范围,它将消除任何可能发出的警告。 .再说一次,如果您想要出于充分的理由使用这样的值,那么消除警告是好的。

在您编辑的示例中,它恰好是一个模板函数而不是一个重载函数,您确实可以替代强制转换:do_something<unsigned short>(23) .使用重载函数,您仍然可以避免强制转换:

void (*f)(unsigned short) = &do_something;
f(23);

...但我不建议这样做。如果没有别的,这仅适用于 unsigned short version 确实存在,而使用强制转换的调用执行通常的重载解决方案以找到最兼容的可用版本。

关于c++ - 如何写一个无符号的短整型文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1329163/

相关文章:

java - Apache Camel 和 Spring 的类型转换问题

c++ - 使用指针传递 QObject (Qt)

C++/Qt 对网络状态改变使用react

c++ - Boost 跳过解析器是正确的方法吗?

c# - 从字节转换 unicode 字符

java - 这一行中的 "int"是什么?

c++ - openAL c++ 库比较两个音频文件

c++ - 我可以重载插入运算符以采用模板化 STL 容器吗?

C# 可互换属性

haskell - 我怎样才能给这个子函数一个显式类型?