gpt4 book ai didi

c++ - 用户定义的文字如何与数字分隔符一起使用?

转载 作者:太空狗 更新时间:2023-10-29 20:54:02 26 4
gpt4 key购买 nike

我只是通过向用户定义的文字添加一个数字分隔符来修改我的代码的一个旧示例,由可变参数模板解析:

namespace lits {
// helper for 1 arg
template<char C> int bin(); // common
template<> int bin<'1'>() { return 1; } // spec.
template<> int bin<'0'>() { return 0; } // spec.
// helper 2 or more args
template<char C, char D, char... ES>
int bin() {
return bin<C>() << (sizeof...(ES)+1) | bin<D,ES...>() ;
}
// operator"" _bin
template<char...CS> int operator"" _bin()
{ return bin<CS...>(); };
}
int main() {
using namespace lits;
int number = 1000'0000_bin; // <<< I added a ' here
}

天哪,g++6.2.0 试图实例化 bin<'\''> 时我很惊讶.它试图通过 '作为 char到我的模板 template<char...CS> int operator"" _bin() !我用 clang++-3.9msvc++-19.00 试过了,同样的提示,这真的让我怀疑。

我觉得这可能不是正确的行为。如果我的文字用引号引起来,我会理解的,比如说 "1000'0000"_bin , 但模板运算符""不存在这种形式,对吗?

我是否期待数字分隔符 '现在也在我的模板用户文字运算符中?

更新 1:以防 '没问题:

可以将 digit-sep 用作各种事物的 sep,例如,复数。 52.84+67.12i 的“52.84'67.12_i'”的行为是否被明确定义?

更新 2:作为对一些评论的回应。以下编译:

#include <iostream>
#include <string>
using std::string;

namespace lits {
// helper
template<char C> string sx() { return string{}+C; }
// helper 2 or more args
template<char C, char D, char... ES>
string sx() {
return sx<C>() + sx<D,ES...>();
}
// operator"" _sx
template<char...CS> string operator"" _sx()
{ return sx<CS...>(); };
}
int main() {
using namespace lits;
std::cout << 10000000_sx << '\n';
std::cout << 10'000'000_sx << '\n';
std::cout << 0x00af_sx << '\n';
std::cout << 0x0'c'0'a'f_sx << '\n';
std::cout << 007_sx << '\n';
std::cout << 0b01_sx << '\n';
// the following do not work:
//std::cout << 0b0a8sh3s1_sx << '\n';
//std::cout << "abcde"_sx << '\n';
}

输出是:

10000000
10'000'000
0x00af
0x0'c'0'a'f
007
0b01

这意味着模板获取所有字符:前缀和数字分隔符——所有这些。 (g++-6.2.0)

正如@krzaq 的回答所暗示的,这似乎是 Std 的计划,因此可以信赖。

最佳答案

据我所知,是的。正如 here 所解释的,数字分隔符是用户定义的整数文字的合法成员。

模板整型字面量定义为:

N4140 § 2.13.8 [lex.ext] / 3

Otherwise (S contains a literal operator template), L is treated as a call of the form

operator "" X <’c1’, ’c2’, ... ’ck’>()

where n is the source character sequence c1c2...ck. [ Note: The sequence c1c2...ck can only contain characters from the basic source character set. —end note ]

没有关于删除分隔符的字样。

关于c++ - 用户定义的文字如何与数字分隔符一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40576175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com