是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
Is there a workaround to define a user-defined literal for shorts in c++?
我想为短裤定义一个用户定义的文字。就像这样:
short operator"" _s(int x)
{
return (short) x;
}
为了定义这样的短:
auto PositiveShort = 42_s;
auto NegativeShort = -42_s;
但是,正如本文所解释的,C++11标准禁止上述用户定义文字的实现:
根据 C++11 标准关于用户定义文字的第 13.5.8./3 段: 文本运算符的声明应具有等效于以下内容之一的参数声明子句:
const char* unsigned long long int long double char wchar_t char16_t char32_t const char*, std::size_t const wchar_t*, std::size_t const char16_t*, std::size_t const char32_t*, std::size_t
对于正面情况,我可以只使用unsigned long long int
但这不适用于负面情况。有没有解决方法可以使用较新的 c++ 未来?
正如这里所解释的,一元-
应用于42_s
的结果,所以似乎无法避免积分提升。根据应用程序的不同,以下解决方法可能会有所帮助:
struct Short {
short v;
short operator+() const {
return v;
}
short operator-() const {
return -v;
}
};
Short operator"" _s(unsigned long long x) {
return Short{static_cast<short>(x)};
}
auto PositiveShort = +42_s;
auto NegativeShort = -42_s;
static_assert(std::is_same_v<decltype(PositiveShort), short>);
static_assert(std::is_same_v<decltype(NegativeShort), short>);
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 'short int'持有的值溢出,但"自动"不会溢出?
- 在类定义之后定义一个私有方法
- 是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
- 对'icu_56::UnicodeString::UnicodeString(signed char, unsigned short const*, int)' 的未定义引用
- 是实现定义的unsigned short + int类型