Reputation: 65
I am getting no instance of constructor "MyClass<t>::MyClass [with t=double]" matches the argument list -- argument types are: (MyClass<int>)
.
I just want to copy one object's value into another. It work fine without template syntax.
#include <iostream>
using namespace std;
template<class t>
class MyClass{
t x,z;
public:
MyClass(){}
MyClass (const t a,const t b):x(a),z(b) {
}
MyClass(const MyClass& obj){
x=(t) obj.x;
z=(t)obj.z;
}
// access content:
void content() {
cout<<x<<z<<endl;
}
};
int main () {
MyClass<int> foo(34,23);
MyClass <double> bar(foo);
bar.content();
foo.content();
return 0;
}
I have searched so many questions/answers related to it but i don't find solution
Upvotes: 3
Views: 20738
Reputation: 85767
The problem is that MyClass<int>
and MyClass<double>
are different types, and you only have a copy constructor that takes objects of the same type.
To get your code to work, I had to change two things:
template<typename u>
MyClass(const MyClass<u>& obj){
x=(t) obj.x;
z=(t)obj.z;
}
Now the constructor is templatized itself (independently of the class). This lets you construct a MyClass<A>
from a different type MyClass<B>
.
But just doing that leads to another error:
prog.cpp:14:19: error: ‘int MyClass<int>::x’ is private within this context
x=(t) obj.x;
Because we're constructing from an object of an unrelated type, we don't have access to private members.
Workaround: Add a friend
declaration in the class:
template<typename> friend class MyClass;
Upvotes: 3
Reputation: 122516
MyClass
is a template. When you write MyClass
inside its declaration, this is actually short-hand for MyClass<T>
, hence MyClass<double>
has no constructor taking a MyClass<int>
.
If you want to allow conversions you need a second template parameter, eg
template <typename T>
struct foo {};
template <typename R,typename T>
foo<R> convert_foo(const foo<T>& f) { return {}; }
Upvotes: 0