简体   繁体   中英

How to pass structure with template variable as an argument inside member function of class in c++?

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;
}

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 . 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"; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM