template argument

hi gyz. can someone help me, this code get error 2768(illegal use of explicit template arguments) and i dont know why :-??
plz help for function template, i know i can use class/struct to solve it.
tnx

template <int i, int j>
void fn()
{
cout << "1 ";
fn<i + 1, j>();
}

template <int j>
void fn<j, j>()
{
cout << "2 ";
}

int main()
{
fn<0, 4>();
}
Last edited on
https://ideone.com/VIZgjT
error: non-class, non-variable partial specialization ‘fn<j, j>’ is not allowed
What you are trying to do is not allowed. See: https://stackoverflow.com/a/33753272/1959975
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

namespace detail
{
    template < int I, int J > struct helper
    {
        static_assert( I < J, "this leads to infinite recursion" ) ;
        static void fn() { std::cout << I ; helper< I+1, J >::fn() ; }
    };

    template < int I > struct helper<I,I>
    {
        static void fn() { std::cout << I << " - we are done\n" ; }
    };
}

template < int I, int J > void fn() { detail::helper<I,J>::fn() ; }

int main()
{
    fn<0,4>() ;
}

http://coliru.stacked-crooked.com/a/6d5716619e724423
@ahura, what are you actually trying to do? (as opposed to what your code looks like).

Did you simply mean
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

template <class T > void fn( T i, T j )
{
   cout << i;
   if ( i < j ) fn( i + 1, j );
}

int main()
{
   fn( 0, 4 );
}


01234


or maybe ...
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

template <int J> void fn( int i )
{
   cout << i;
   if ( i < J ) fn<J>( i + 1 );
}

int main()
{
   fn<4>( 0 );
}

Last edited on
I'm bemused, but this actually worked on both compilers that I tried ...
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

template <int I, int J> void fn()
{
   cout << I;
   if ( I < J ) fn< I + 1 < J ? I + 1 : J, J>();
}

int main()
{
   fn<0,4>();
}


It seemed to be enough to stop the infinite recursion.
Last edited on
Topic archived. No new replies allowed.