Saturday, May 9, 2009

What does it mean in C++ that template definitions cannot nest?

im working on a program for my computer class and i get this error and im probably being stupid but i can figure it out. any help?

What does it mean in C++ that template definitions cannot nest?
It doesn't mean anything because templates can be nested... post your code and we'll help you.
Reply:This error is usually a follow up error indicating something else is wrong. Please read this post from experts exchange:





Q:


Please help resolve problems with this code. I am getting two errors


I am using VS6.0 SP6


Many Thanks


-----------------------------





//Parameter values for templates


//Besides the template arguments preceded by the class or typename keywords that represent a type, function templates and class templates can include other parameters that are not types whenever they are also constant values, like for example values of fundamental types.





// array template


#include %26lt;iostream%26gt;


using namespace std;








template %26lt;class T, int N%26gt;


class array {


T memblock [N];


public:


void setmember (int x, T value);


T getmember (int x);


};





template %26lt;class T, int N%26gt;


array%26lt;T,N%26gt;::setmember (int x, T value) {


memblock[x]=value;


}





template %26lt;class T, int N%26gt;


T array%26lt;T,N%26gt;::getmember (int x) {


return memblock[x];


}





int main () {


array %26lt;int,5%26gt; myints;


array %26lt;double,5%26gt; myfloats;


myints.setmember (0,100);


myfloats.setmember (3,3.1416);


cout %26lt;%26lt; myints.getmember(0) %26lt;%26lt; '\n';


cout %26lt;%26lt; myfloats.getmember(3) %26lt;%26lt; '\n';


return 0;


}


-----------------------------


Errors I am getting:


'array%26lt;T,N%26gt;::setmember' : unable to resolve function overload


D:\Manpreet\My CPP\Templates1\template.cpp(24) : error C2954: template definitions cannot nest


Error executing cl.exe.


------------------------------





Answer: Problem is with definition of setmember method. It should be:





template %26lt;class T, int N%26gt;


void array%26lt;T,N%26gt;::setmember (int x, T value) {


memblock[x]=value;


}





You forgot to specify the 'void' return type for 'setmember()', thus the compiler assumed 'int'.





Abt the errors:


%26gt;%26gt;'array%26lt;T,N%26gt;::setmember' : unable to resolve function overload





That leads to the return type...





%26gt;%26gt;error C2954: template definitions cannot nest





... and that was a followup error, since





array%26lt;T,N%26gt;::setmember (int x, T value)





*without* the return type looks like a nested template...

bouquet

No comments:

Post a Comment