Template problem question

This is a discussion on Template problem question within the C++ Programming forums, part of the General Programming Boards category; Dear all, I would like to ask if it is possible to have a template function as a general function ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    16

    Template problem question

    Dear all,

    I would like to ask if it is possible to have a template function as a general function for two functions that have a different return type.
    For example:
    int AddNumbers(int a, int b);

    float AddFloats(float a, float b);

    What would it be the template function for the above example?

    Regards,
    grscot

  2. #2
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    so long as all operations and methods used in the template function for a given data type T are defined, you can use it as T.

    in the case of Add()

    certainly, "+" is defined for float and int so it would work. very trivial example though.

    template <class T>
    T Add(T var1, T var2)
    {
    return var1 + var2;
    }
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  3. #3
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856

    Re: Template problem question

    Code:
    template <typename T>
    T add(T a, T b) { return a + b; }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with script!
    By Cherry65 in forum C++ Programming
    Replies: 10
    Last Post: 12-18-2008, 10:05 AM
  2. linked list and template problem
    By f6ff in forum C++ Programming
    Replies: 2
    Last Post: 04-03-2006, 10:56 AM
  3. function template question
    By Thantos in forum C++ Programming
    Replies: 3
    Last Post: 04-18-2004, 10:40 AM
  4. question about .net to 6.0 change causing errors
    By jverkoey in forum C++ Programming
    Replies: 17
    Last Post: 03-23-2004, 09:45 AM
  5. Replies: 4
    Last Post: 03-21-2004, 02:34 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21