Why does the compiler complain that f () is not displayed?

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

The compiler complains about line 8:

 f< N - 1 >(); 

A function call f that is not visible in the template definition and ADL not found.

+8
c ++ c ++ 11 templates
source share
2 answers

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 prototype for function version N==1 .

+4
source share

Reorder the 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 
+10
source share

All Articles