是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?

Is there a workaround to define a user-defined literal for shorts in c++?

本文关键字:定义 short 用户 文字 中为 c++ 解决 方法 是否      更新时间:2023-10-16

我想为短裤定义一个用户定义的文字。就像这样:

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>);