Amir
Amir

Reputation: 2258

Dealing with strings in c++ template

As part of some beginner c++ template exercises, I'm trying to write a template as a wrapper for std::vector in c++, and I've come across a snag.

Say the types of variables I'll be using are int, double and string.

I'm trying to write a loop to fill in the vector:

type element;

while (element != 0){
  std::cout << "Enter an element, use 0 to exit: ";
  std::cin >> element;

  if(element != 0)
    items.push_back(element);
}

The problem is, while this works for int & double, it doesn't work with std::string, as string doesn't support !=. I can also see myself having problems with working out the largest/small value in the vector.

What is the best way to get around this issue?

Upvotes: 0

Views: 159

Answers (1)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16017

You could provide an optional template argument which is a comparator (I think the standard lib does that frequently). Less ambitiously, you could use type{} to compare against which should work for anything with a default ctor: if(element != type{}). (Your problem is not that string doesn't have a comparison operator but that the operators aren't defined for comparisons with ints).

Upvotes: 3

Related Questions