Thread: Different return types in Template function

  1. #1
    Registered User
    Join Date
    Dec 2005

    Different return types in Template function

    Hi, it's my first post and question.

    I have a template class that is going to be inherited by some other class. Within the parent class, I have a function:

    template <class T>
    T   MyClass<T>::GetData ( int tag )
     int index = GetIndex( tag );
     if(index == NO_INDEX ) return NULL;
    Now, class T could be anything and specifically I want T to be <int> or
    <MyCustomClass *>.

    Now in the 5th line, it is checking for out of bounds error. The question is I do not know what to return if there is out of bounds. I have NULL for now, but if T is not a pointer, the program won't like it.

  2. #2
    Registered User
    Join Date
    Jun 2005
    You might also try throwing an exception .....

  3. #3
    Registered User
    Join Date
    Dec 2005
    Yes, that what I decided to do. I'll throw an exception
    and for each derived class, I'll wrap around that function and handle any errors.

  4. #4
    Registered User
    Join Date
    Jan 2005
    If VectorOfT is a vector, then you don't have to check the bounds. The at() function will check the bounds and throw an exception for you.

    If you'd prefer to have your function not throw an exception, then you could return T() which returns a default initialized value. If T is an int, it will return 0, if it is a pointer it will return 0 (a null pointer). If T is a class type, it will return a default constructed object. This would add a requirement to T that it be default constructable (if that isn't already required).

    You should also use [] instead of at() if you are going to check for all out of bounds indexes yourself, since you wouldn't need the bounds checking frorm at(). Of course, the current code only checks for one type of bad index, so at() is more comprehensive than that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  2. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM