I would like to pass 'structure with template variable' as an argument inside member function of class. I am getting error "no matching function for call to". Can anyone help me? I am doing some mistake either in declaration / definition / while passing argument from the main.
template <typename T>
struct msg_1{
int var_1;
int var_2;
T *var_3;
};
template<typename T>
struct msg_2{
int var_1;
int var_2;
T *var_3;
};
class A
{
public:
int a;
int b;
template <typename T>
void test(T *, T *);
};
template <typename T>
void A::test(T *t1, T *t2)
{ cout<<"Inside test @todo Do something"; }
int main()
{
A ob;
ob.a=10;
ob.b=20;
msg_1<int> *ob_1 = new msg_1<int>;
msg_2<int> *ob_2 = new msg_2<int>;
ob.test(ob_1,ob_2);
return 0;
}
======== I have accepted the given suggestion and modified the code, but getting some error while implementing. Kindly have a look.
I have passed the structure as a parameter in test method like below
template <typename T>
struct msg1{
…
};
template<typename U>
struct msg2{
…
};
struct msg3
{
uint16_t var_4;
};
class A
{
public:
int a;
int b;
template <typename T, typename U>
void test(msg1<T> *t1, msg2<U> *t2);
};
template <typename T, typename U>
void A::test(msg1<T> *t1, msg2<U> *t2)
{
cout<<"Inside test @todo Do something";
}
int main()
{
A ob;
ob.a=10;
ob.b=20;
msg_1<msg3> *ob_1 = new msg_1<msg3>;
msg_2<msg3> *ob_2 = new msg_2<msg3>;
ob.test(ob_1,ob_2);
return 0;
}
When I am running above code in online compiler then it’s running fine but when I am implementing it in actual code to do testing then I am getting compile time error “undefined reference to ‘void A::test< msg3, msg3 > ( msg1 *, msg2 * )’. Can anyone please tell me what possibly I am doing wrong.
CodePudding user response:
Your template function A::test
is only templated with one type T
and requires that both parameters have the same type T*
. In your example you pass different parameters: msg_1<int> *
and msg_2<int> *
.
If you really want test
to only accept two parameters with identical type, then you can't pass ob_1
and ob_2
. If you want test
to accept two parameters of different type, then you can change your class A
and function A::test
as follows.
class A
{
public:
int a;
int b;
template <typename T1, typename T2>
void test(T1 *, T2 *);
};
template <typename T1, typename T2>
void A::test(T1 *t1, T2 *t2)
{ cout<<"Inside test @todo Do something"; }