2
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 页

4

1 回答 1

0

模棱两可的原因是,对于类似的调用有两个同样好的匹配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...>();
}
于 2015-01-01T08:17:07.717 回答