Boost logo

Boost :

From: Krishna Achuthan (TT) (Krishna.Achuthan_at_[hidden])
Date: 2004-03-10 11:12:55


David Abrahams wrote:

>"Allen Yao" <yaozhen_at_[hidden]> writes:
>
> > It seems that gcc does not allow this kind of template argument
deduction:
> >
> > template <int N>
> > void f(int a[N])
> > {
> > for (int i = 0; i < N; i++)
> > cout << a[i] << " ";
> > cout << endl;
> > }
> >
> > int main()
> > {
> > int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
> >
> > f(a);
> > }
> >
> > The error message is:
> >
> > error: no matching function for call to `f(int[10])'
> >
> > I would like to know how to fix this. Is there any workaround?
> > Or if I am missing something?
>
> You're missing something. Your declaration of f is equivalent to:
>
> template <int N>
> void f(int* a);
>
> try:
>
> template <int N>
> void f(int a(&)[N])
> ^^^
> instead.
>

I tried both the original problem and the proposed solution on VC 7.1

For the original problem I got the following error messages:
c:\Krishna\Console\Console7.cpp(242) : error C2784: 'void f(int [N])' :
could not deduce template argument for 'int [N]' from 'int [10]'
c:\Krishna\Console\Console7.cpp(207) : see declaration of 'f'

And when I tried the proposed solution, I got the following error messages:
c:\Krishna\Console\Console7.cpp(209) : error C2988: unrecognizable template
declaration/definition
c:\Krishna\Console\Console7.cpp(209) : error C2059: syntax error : '&'
c:\Krishna\Console\Console7.cpp(209) : error C2090: function returns array
c:\Krishna\Console\Console7.cpp(241) : error C2783: 'void f(int *(__cdecl
*)(void))' : could not deduce template argument for 'N'
c:\Krishna\Console\Console7.cpp(209) : see declaration of 'f'

I did manage to find a work-around, which goes like this:
 
template<class T>
struct F;

template<class T, int N>
struct F<T[N]>
{
  void operator()(T a[N])
  {
    for (int i = 0; i < N; i++)
      cout << a[i] << " ";
      cout << endl;
  }
};

template<class T>
void f(T& a)
{
        F<T>()(a);
}

int main()
{
  int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  f(a);
}

Does it help?

- Krishna Achuthan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk