0
using namespace std;

template <typename T>
void add(linked<T> &list1,ifstream& myFile){
    string a;
    while(!myFile.eof()){ 
    myFile >> a;
    T car1;
    car1.setName(a);
    T& car2 = car1;
    list1.addtolist(car2);
    }
}

int main(){
    linked<car> list1;
    ifstream myFile;
    myFile.open("car.txt");
    add(list1,myFile);
    cout << (list1.getElem(1)).getName() << endl;
}

car is a class having a parameter, now I want to pass a list having a class(say bus) object of two parameters and want to read the parameters from a file. How can I change the add function so that it takes one input in case of car and two inputs in case of bus

P.S. linked is linked list class.

Basically , I want to create a function which takes one input if class is car(i.e template T is car) and two inputs if the class is bus.

Ram Sharma
  • 67
  • 2
  • 10
  • 1
    Please take some time to read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Sep 07 '17 at 12:02
  • 1
    As for your problem, perhaps use inheritance, polymorphism and pointers to the common base-class? Also do some reading about operator overloading, so you can do e.g. `car c; myFile >> c;`. Any [good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should tell you all about this. – Some programmer dude Sep 07 '17 at 12:03
  • You may use overloads. – Jarod42 Sep 07 '17 at 12:20
  • @Jarod42 How ?? – Ram Sharma Sep 07 '17 at 12:31

2 Answers2

1

Provide overloads:

std::istream& operator >> (std::istream& is, Car& car)
{
    std::string s;
    is >> s;
    car.setName(s);
    return is;
}

std::istream& operator >> (std::istream& is, Bus& bus)
{
    std::string s;
    std::string s2;
    is >> s >> s2;
    bus.setName(s);
    bus.setProperty(s2);
    return is;
}

and then

template <typename T>
void add(linked<T>& myList, std::istream& myStream){
    while (myStream) {
        T t;
        myStream >> t;
        myList.addtolist(t);
    }
}
Jarod42
  • 173,454
  • 13
  • 146
  • 250
0

Create a template initialize function

template<typename T>
T CreateFromFileStream(ifstream& myFile);

template<>
car CreateFromFileStream(ifstream& myFile)
{
  std::string a;
  myFile >> a;
  car myCar;
  myCar.setName(a);
  return myCar;
}

template<>
bus CreateFromFileStream(ifstream& myFile)
{
  ...
}

template <typename T>
void add(linked<T> &list1,ifstream& myFile){
    while(!myFile.eof()){ 
      list1.addtolist(CreateFromFileStream<T>(myFile);
    }
}
MikeySans
  • 11
  • 1