我想为短裤定义一个用户定义的文字。就像这样:
short operator"" _s(int x)
{
return (short) x;
}
为了定义这样的简短:
auto PositiveShort = 42_s;
auto NegativeShort = -42_s;
但是,正如 this post 中所述C++11 标准禁止用户定义文字的上述实现:
Per paragraph 13.5.8./3 of the C++11 Standard on user-defined literals: The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of the following:
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++ future 的解决方法?
最佳答案
如上所述here ,一元 -
应用于 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>);
关于c++ - 是否有解决方法可以在 C++ 中为 Shorts 定义用户定义的文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238958/