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

She*_*win 8 c++ templates c++11

#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>();
}
Run Code Online (Sandbox Code Playgroud)

编译器在第8行抱怨:

f< N - 1 >();
Run Code Online (Sandbox Code Playgroud)

调用f在模板定义中既未显示也未找到的函数ADL.

Ada*_*dam 10

颠倒函数定义的顺序.

#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>();
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./a.out
3 2 1 1
Run Code Online (Sandbox Code Playgroud)

  • ...或者转发声明N == 1版本. (2认同)

Try*_*ard 4

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

您有两种可能的方法:

方法一:

#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>();
}
Run Code Online (Sandbox Code Playgroud)

方法二:

您可以转发声明版本函数的原型N==1