gpt4 book ai didi

c++ - 为什么编译器提示 f() 不可见?

转载 作者:可可西里 更新时间:2023-11-01 17:31:07 26 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

template <size_t N>
typename enable_if<(N > 1), void>::type f(){
cout << N - 1 << ' ';
f<N - 1>();
}
template <size_t N>
typename enable_if<N == 1, void> ::type f() {
cout << 1;
}
int main() {
f<4>();
}

编译器在第 8 行报错:

f< N - 1 >();

Call to function f that is neither visible in the template definition nor found by ADL.

最佳答案

反转函数定义的顺序。

#include <iostream>
#include <type_traits>

using namespace std;

template <size_t N>
typename enable_if<N == 1, void> ::type f() {
cout << 1;
}
template <size_t N>
typename enable_if<(N > 1), void>::type f(){
cout << N - 1 << ' ';
f<N - 1>();
}
int main() {
f<4>();
}

输出:

$ ./a.out
3 2 1 1

关于c++ - 为什么编译器提示 f() 不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065378/

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