Advertisement

Problem with templates

Started by March 09, 2003 02:53 PM
2 comments, last by al_le 21 years, 8 months ago
Hello! I have a small problem with templates. This is the first time I try to make one and doesn''t work. Heres the code (i know its ugly) #include <iostream> using namespace std; template void Add(T*, int); int main(void) { int tar[10]; int i; for(i = 0; i < 10; i++) tar = i * 2; Add(tar, 10); return 0; } template void Add(T* target, int size) { for(int i=0; i < size; i++) ++target; } I don''t know what the problem is but i cannot compile it. </i>
Hmmm, where did you learn to write templates like that?

Anyway, it would look more like this:


  template<class T>void Add(T* target, int size){    for(int i=0; i < size; i++)        ++target[i];}  
Advertisement
Add<int*>(tar, 10);template<class T> void Add(T* target, int size) 


Since you''re explicitely specifying int* as the template parameter (hint: you don''t have to), the compiler expects target to be an int**. Which tar isn''t : it''s an int[10], which decays into an int*.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks for the help.

This topic is closed to new replies.

Advertisement