Neelesh wrote:
> Hi all,
> I had some confusion about deduction of non-type template parameters
> for function templates :
>
> template <class T, int i> void foo (T, int p = i) ;
>
> void bar()
> {
> foo<int, 10>(40,40); // OK, T = int, i = 10
> foo(40,40); // ERROR, T = int but i cannot be deduced.
> }
The compiler cannot deduce non-type parameters for function templates
since there is no requirement that the parameters be compile-time
constants. Moreover, non-type template parameters are not all that
useful. Why call one routine when the parameter is 40 and a different
routine when it is 20? Aren't parameters supposed to be variables?
Can't one routine accept both a 20 or a 40 as a parameter?
Even if the routines should be distinct, they need not be function
templates. One function could be named Function20 and the other
Function40. Non-type function templates provide no more abstraction
than parameter-accepting functions, but can easily add significantly
more bloat to an application.
> However here I have another example :
>
> template <class T, int i> void lookup ( Buffer<T,i> b);
>
> void bar(Buffer<int, 128> b)
> {
> lookup(b,100); // No error, can infer T = int, i = 128
> }
>
> So it seems that when 'i' gets inferred as a "side effect" of type
> matching, the compiler accepts that. However, it doesnot try to infer
> it explicitly if required.
The compiler deduces that the type Buffer<int, 128> - so the 128 is
deduced from the type of the parameter. You want the compiler to deduce
40 from the value of the parameter - a completely different
proposition.
Greg
|