C++: "expected ;" in declaration in template -


i've been running following problem inside member function of templated class:

#include <map> using std::map; template <typename a,typename b> class c {   public:     b f(const a&,const b&) const;   private:     map<a,b> d; }; template <typename a,typename b> b c<a,b>::f(const a&a,const b&b) const {    map<a,b>::const_iterator x = d.find(a);    if(x == d.end())      return b;    else      return x->second; } 

when have g++ compile following error:

bug.c: in member function 'b c<a,b>::f(const a&, const b&) const': bug.c:12: error:expected ';' before 'x' bug.c:13: error: 'x' not declared in scope 

however, when make non-templated version of class , function, , b both being int compiles without problem. error little mystifying since can't imagine why wants ';' before 'x'.

you're missing typename:

typename map<a,b>::const_iterator x = d.find(a); 

please read where , why have put “template” , “typename” keywords?. reason need typename here because a , b template parameters means meaning of ::const_iterator depends on a , b are. while human name const_iterator makes obvious iterator type, compiler doesn't know if type, data member, etc.

the compiler syntax check on first pass before templates instantiated , adding typename letting compiler know parse map<a,b>::const_iterator type.

also, there special rule in c++ (shamefully stolen linked question):

a name used in template declaration or definition , dependent on template-parameter assumed not name type unless applicable name lookup finds type name or name qualified keyword typename.

if not add typename, compiler has assume not type.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -