gpt4 book ai didi

c++ - 文字运算符的模板参数列表

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

这是我将二进制文字转换为十进制的实现:

template<char Head, char... Tail>
constexpr int operator"" _b()
{
if constexpr (sizeof... (Tail) == 0)
{
return Head - '0';
}
else
{
return (Head - '0') * (1 << sizeof...(Tail)) + operator"" _b<Tail...>();
}
}

GCC compiles happily ,

同时 Clang fails :

prog.cc:1:2: error: template parameter list for literal operator must be either 'char...' or 'typename T, T...'
template<char Head, char... Tail>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:19:27: error: no matching literal operator for call to 'operator""_b' with argument of type 'unsigned long long' or 'const char *', and no matching literal operator template
std::cout << 110110110_b;
^

icc also fails :

error: a literal operator template must have a template parameter list equivalent to "<char ...>"

constexpr int operator"" _b()

^

MSVC also fails:

<source>(2): error C3686: 'operator ""_b': literal operator template must have exactly one template parameter that is a parameter pack

因此,icc 需要 char... 而 clang 和 msvc 需要 typename T, T...char...,只有 gcc 允许我的 HeadTail

解决方法应该很简单——只需将 char Head, char...Tail 替换为 char...digits 并返回一个新的 aux 函数,使用 char Head, char...Tail 作为模板参数,或者使用结构特化 headhead, tail... 没有 if constexpr

但我没有从标准草案中找到相关要求。你能告诉我哪个符合标准吗?当然,如果您有更优雅的解决方案(除了我上面提到的两个)不会调用编译器错误,请粘贴在这里,我将非常感激。

最佳答案

标准在 [over.literal]/5 中非常明确地说明了这一点:

The declaration of a literal operator template shall have an empty parameter-declaration-clause and its template-parameter-list shall have a single template-parameter that is a non-type template parameter pack with element type char.

所以 GCC 允许这样做是错误的。

关于c++ - 文字运算符的模板参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789050/

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