OK, I've been looking at templates recently and eveything was fine...never had a problem with them at any point. But then when I decided to write a function that would either return the given template type or not. the following code explains what I mean.

template <class T>
T find(char x, T array[]){
  string str = "hello";
  for(int i = 0; i < str.length(); i++){
     if(x == str[i]) return array[i];
  }
  // if it's not I need to return something...but what?
}

I hope that makes sense all thanks

Chris

Recommended Answers

All 4 Replies

Maybe return an index or value that will never be used, for example, if T = int, return (-1 for example), and then the caller can do a check to see if a value was found, if not, -1 is returned.

I had already though of that, but what if T is a string? Since T could be absolutely anything I don't know what to do, it could be a class..

class...hmm maybe I should just return the default constructor for T?
T();

Chris

>maybe I should just return the default constructor for T?
You could do that, and add a parameter for the caller to check if anything was found, like this:

template <class T>
T find(char x, T array[], bool &found){
  string str = "hello";
  found = true;
  for(int i = 0; i < str.length(); i++){
     if(x == str[i]) return array[i];
  }
  found = false;
  // Return default constructor
}

Yer I think i'm going to go with something like that. Although it will be slightly different i'll just have a variable within my class that marks if it was found or not. Since that was only an example i'm actually overloading the operator[] so passing another parameter is kind out of the question lol.

Thanks for the input
Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.