Couldn’t find anything relevant in forums So ,Please help me with this code .I’m brushing up my c++ concepts and met with a strange error
#include<iostream>
using namespace std ;
class base
{
int i ;
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 to compile with the following error :
test.cpp: In function ‘int main()’:
test.cpp:28: error: no matching function for call to ‘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 and arrive at an answer at to why did this happen .If i instantiate a new base class from the template , everything works just fine , but not this one .
Can somebody tell me a good source for template instantiations and what are the rules/semantics , what is happening behind the curtain ?
thanks
baseis not a completederivedtype, so you’ll have to provide a constructor inside your template that fills in the missing details.When you create an instance of this template based on
derived, the compiler translates it to a class, which essentially boils down to thisThe default constructor is not generated any more. However, a default copy constructor is still created.
As you can see, there is no way to pass base (by reference or copy) into the class.
The solution is to provide a constructor inside your template that fills in the missing details:
By the way, your
baseshould most likely have a virtual destructorand
test(T b)should betest(T const& b)