gpt4 book ai didi

c++ - 空值包扩展是否匹配类型包或可选类型参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:36:15 25 4
gpt4 key购买 nike

我只是想破解一个二进制文字 operator ""_b,但在尝试终止递归时遇到了困难。如何定义一个可以使用空的显式模板参数列表调用的函数,它与参数包重载不冲突?然后,灵感:将空包扩展与古怪的东西相匹配。

但是 GCC 提示空参数列表的不存在类型与参数列表的非显式要求类型不一致。它应该以这种方式工作吗?

template< char head, char ... tail >
constexpr unsigned long long parse_binary() {
return ( ( head - '0' ) << sizeof ... (tail) )
+ parse_binary< tail ... >(); // Error: no overload for termination.
}

template< typename = void > // I want this to match an empty pack of chars.
// template< short = 0 > // even this would do.
constexpr unsigned long long parse_binary() {
return 0;
}

template< char ... digits >
constexpr unsigned long long operator ""_b() {
return parse_binary< digits ... >();
}

#include <iostream>

int main() {
std::cout << 010101_b << '\n';
}

注意:问题不是实现 operator ""_b。这个问题可以通过将包扩展到参数列表并传递 std::integral_constant 类型来解决。

注意 2:此代码实际上确实可以进行较小的调整;请参阅下面的答案。但这并没有直接解决问题。嗯,也许我应该编辑这个而不是回答......

最佳答案

在一个字符处终止递归不是更好吗?

template<char Ch>
constexpr unsigned long long parse_binary(){
return Ch - '0';
};

// second head to disambiguate
template< char head1, char head2, char ... tail >
constexpr unsigned long long parse_binary() {
return ( ( head1 - '0' ) << sizeof ... (tail)+1 ) + parse_binary< head2, tail ... >();
}

无论如何,问题是零字符的 parse_binary 需要在可变参数版本之前声明,正如 Clang 很好地指出的那样:

error: call to function 'parse_binary' that is neither visible in
the template definition nor found by argument-dependent lookup

// call trace...

note: 'parse_binary' should be declared prior to the call site
constexpr unsigned long long parse_binary() {

关于c++ - 空值包扩展是否匹配类型包或可选类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500611/

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