Pot*_*ter 5 c++ templates variadic-templates c++11
我只是试图破解二进制文字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';
}
Run Code Online (Sandbox Code Playgroud)
注意:问题不在于实施operator ""_b.这个问题可以通过将包扩展到参数列表并传递std::integral_constant类型来解决.
注2:此代码实际上可以进行微调; 请参阅下面的答案.但这并没有直接解决这个问题.嗯,也许我应该编辑这个而不是回答...
没有官方说明这种棘手匹配的合规性,但如果两个重载被调换,给定的代码确实可以工作。
第二个终止重载对第一个重载不可见,因为第一个重载在模板定义时解析名称。只有依赖于模板参数的函数调用才会将查找推迟到实例化时间。
需要明确的是,这是有效的:
template< typename = void > // Define this one first!
constexpr unsigned long long parse_binary() {
return 0;
}
template< char head, char ... tail >
constexpr unsigned long long parse_binary() {
return ( ( head - '0' ) << sizeof ... (tail) )
+ parse_binary< tail ... >(); // Bingo: overload found.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
754 次 |
| 最近记录: |