3
template<class T, T i> void f(int[10][i]) { };

int main() {
   int a[10][30];
   f(a);
}

Why does f(a) fail?

http://ideone.com/Rkc1Z

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
vittorio
  • 33
  • 3

3 Answers3

4

f(a) fails because a template type argument cannot be deduced from the type of a non-type argument. In this case the compiler cannot deduce the type of the template parameter T.

Try calling it as f<int>(a);

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 1
    Mmm suboptimal. It took some tinkering (i.e. reading up), but [there is a good way to do this](http://stackoverflow.com/questions/5771314/no-matching-function-for-call-to-function-template/5771415#5771415). (_The second template param actually should never have been of type T_) – sehe Apr 24 '11 at 15:32
  • Why a downvote? The question asked is why `f(a)` fails and my post manages to answer that. – Prasoon Saurav Apr 24 '11 at 15:35
4

Try this:

template<class T, T i> void f(T[10][i]) { }; // note the 'T'

int main() {
   int a[10][30];
   f(a);
}

.. this enables the compiler to deduce the type of T, which is totally impossible in your sample (because T is not used at all).

http://ideone.com/gyQqI

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
1
template< std::size_t N > void f(int (&arr)[10][N])
{
}

int main() {
   int a[10][30];
   f(a);
}

This one works (http://codepad.org/iXeqanLJ)


Useful backgrounder: Overload resolution and arrays: which function should be called?

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633