0

I am new to Templates and trying to get name and item but I run into weird error. I thought the problem was the string so I changed to int but it didn't work. can you help me please. Thank you! when i delete the templates form cpp class i get many different errors even tho i am defining them in hpp file

Template.hpp

#ifndef Template_hpp
#define Template_hpp

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

template <typename T1 ,typename  T2>
class Temp
{
private:
    T1 item;
    T2 name;

public:
    Temp();
    Temp(T1 item, T2 name);
    T1 getItem();
    T2 getName();

};
#endif /* Template_hpp */

Template.cpp

#include "Template.hpp"
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
template <typename T1 ,typename  T2>
Temp<T1,T2>:: Temp()
{

}
template <typename T1 ,typename  T2>

Temp<T1, T2>::  Temp( T1 item, T2 name)
{
    this->item=item;
    this->name=name;
}
template <typename T1 ,typename  T2>
T1 Temp<T1,T2>:: getItem()
{
    return this->item;
}

template <typename T1 ,typename  T2>
  T2 Temp<T1,T2>::getName()
{
    return this->name;
}

main.cpp

#include <iostream>
#include<string>
#include "Template.hpp"
using namespace std;

int main(int argc, const char * argv[]) {

    //Error here 
    Temp<int,string>t1(10,"zaid");
    t1.getName();
    return 0;
}

Error

Showing All Issues
Undefined symbol: Temp<int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::Temp(int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
  • short answer: templates should be defined in headers only – Sebastian Hoffmann Jun 11 '20 at 20:56
  • when i delete them from cpp class. it doesn't work too! @SebastianHoffmann –  Jun 11 '20 at 20:58
  • You can't just delete them entirely; you need to define them in the .hpp file. – cigien Jun 11 '20 at 21:01
  • @cigien, I am defining them in the .hpp file. i will post my .hpp class so you can see ! –  Jun 11 '20 at 21:02
  • @cigien take a look at it right now, what's wrong with it? thank you! –  Jun 11 '20 at 21:05
  • It's the same issue that is covered in the dupe. Please read that. Even though you have defined the class in the .hpp, you need to define the member functions in the .hpp as well. – cigien Jun 11 '20 at 21:07

0 Answers0