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

标签 c++ user-defined-literals

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

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/

相关文章:

c++ - 错误 : Iso c++ forbids comparison between pointer and integer [c++]

c++ - 在 Linux C++ 中获取 PTY 的最简单方法

c++ - 跨平台构建库而不运行所有平台

c++ - 标准预定义了哪些用户定义文字?

c++ - c++0x 中用户定义文字的重载规则

C++ 11 用户定义文字与 Microsoft Visual Studio 2013

c++ - 在 OpenGL 中填充自相交多边形

c++ - 如何在 C++ 中重载等于运算符?

c++ - 有没有人有关于使用运营商“”的信息?

c++ - 以下包扩展有什么问题?