Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Compiler complains at line 8:

f< N - 1 >();

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

like image 800
Sherwin Avatar asked Aug 18 '15 06:08

Sherwin


2 Answers

Reverse the order of your function definitions.

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

Output:

$ ./a.out
3 2 1 1
like image 146
Adam Avatar answered Sep 21 '22 00:09

Adam


Please note that the function is defined below the function call.

You have two possible approaches:

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

Approach 2:

You can forward declare the prototype for the N==1 version function.

like image 45
TryinHard Avatar answered Sep 23 '22 00:09

TryinHard