为什么编译器抱怨f()不可见?

Why does compiler complain that f() is not visible?

本文关键字:编译器 为什么      更新时间:2023-10-16
#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 >();

调用函数f,该函数在模板定义中既不可见,也无法在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

请注意,函数是在函数调用下面定义的。

有两种可能的方法:

方法1:

#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>();
}

方法2:

您可以前向声明 N==1版本函数的原型