c++ - Doubt with the template instantiation problem in the below snippet of a user defined class -


couldn't find relevant in forums ,please me code .i'm brushing c++ concepts , met strange error

#include<iostream> using namespace std ; class base {     int ; public:     virtual void f(){cout<<"base" ; return ;}; }; class derived: public base { int j ; public:     void f() {cout<<"derived" ; return ;} }; template<class t> class test { public:     test(t b)      {         b.f(); cout<<endl<<" "<<sizeof(b)<<endl;     } }; int main() { base b ; derived d; test<derived> t(b); // cannot instantiate user defined type without typename } 

the following code fails compile following error :

test.cpp: in function ‘int main()’: test.cpp:28: error: no matching function call ‘test<derived>::test(base&)’ test.cpp:19: note: candidates are: test<t>::test(t) [with t = derived] test.cpp:17: note:  test<derived>::test(const test<derived>&) 

i can make wild guess , arrive @ answer @ why did happen .if instantiate new base class template , works fine , not 1 . can tell me source template instantiations , rules/semantics , happening behind curtain ?

base not complete derived type, you'll have provide constructor inside template fills in missing details.

template<class t> //original template class test {   public:     test(t b)     {       b.f();       cout<<endl<<" "<<sizeof(b)<<endl;     } }; 

when create instance of template based on derived, compiler translates class, boils down this

class derivedtest {   public:     derivedtest(derived b)     {       b.f();       cout<<endl<<" "<<sizeof(b)<<endl;     } }; 

the default constructor not generated more. however, default copy constructor still created.

derivedtest::derivedtest(derived const&); 

as can see, there no way pass base (by reference or copy) class.

the solution provide constructor inside template fills in missing details:

template<class t> class test {   public:     test(base const& item)      : base(item)     {     }       test(t b)     {       b.f();       cout<<endl<<" "<<sizeof(b)<<endl;     } }; 

by way, base should have virtual destructor

and test(t b) should test(t const& b)


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -