跟随包扩展有什么问题?

what's wrong with following pack expansion?

本文关键字:什么 问题 扩展 包扩展 跟随      更新时间:2023-10-16
constexpr int ipow(int x, int n) {
    return (n > 0) ? x * ipow(x, n - 1): 1;
}
template <char c>
constexpr int b3_helper() {
    static_assert(c < '3', "not a ternary digit");
    return c - '0';
}
template <char c, char... chars>
constexpr int b3_helper() {
    static_assert(c < '3', "not a ternary digit");
    return ipow(3, sizeof...(chars)) * (c - '0') + b3_helper<chars...>();
}
template <char... chars>
constexpr int operator"" _b3() {
return b3_helper<chars...>();
}
int main(){
    int i = 201_b3;
    return 0;
}

编译器说

在第12行呼唤'b3_helper'是模棱两可的";

我该如何解决它?当我学习C++编程语言 4th 时,我发现了这个问题。在第 560 页

歧义是因为像 b3_helper<'1'> 这样的调用有两个同样好的匹配项 - 第一个函数模板可以与 char c = '1' 匹配,第二个函数模板可以与 char c = '1' 匹配,...是空参数包。要解决此问题,您可以将函数的"归纳"重载更改为需要两个或多个char,如下所示:

template <char c, char d, char... chars>
constexpr int b3_helper() {
    static_assert(c < '3', "not a ternary digit");
    return ipow(3, 1 + sizeof...(chars)) * (c - '0') + b3_helper<d, chars...>();
}