no instance of constructor matches the argument list -- argument types are:
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;
Related videos on Youtube

core
Updated on July 14, 2022Comments
-
core 10 months
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
-
core over 4 yearsThank you sir/ma'am .It help me
-
core over 4 yearsI think it works but problem will be accesing private variable
-
core over 4 years
code
template<class u,class m> void fun(MyClass<u> & obj1, const MyClass<m> &obj2){ obj1.x = (u) obj2.x; obj1.z = (u) obj2.z; }code
-
463035818_is_not_a_number over 4 years@thesummer I just wanted to show how it could be done. was planning to improve it, but the other answer already shows how to use the constructor, example was mainly to demonstrate the use of a second template parameter