How do you decide whether to use templates or overloaded function

This is a discussion on How do you decide whether to use templates or overloaded function within the C++ Programming forums, part of the General Programming Boards category; Folks, Could anyone help me understand how do you decide whether to use templates or overloaded function? I was asked ...

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    4

    How do you decide whether to use templates or overloaded function

    Folks,

    Could anyone help me understand how do you decide whether to use templates or overloaded function? I was asked this question in an interview and couldn't answer. This is the scenario:

    Given an algorithm, how do you decide whether to use a template method or overloaded function?

    Thanks for your insights!

  2. #2
    ---
    Join Date
    May 2004
    Posts
    1,379
    Someone may give a better explanation but I would say that, using a template would mean you only have to implement the function once rather than many times for different types in the case of overloaded functions.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I'd say, if the new functions take exactly the same number of parameters and do exactly the same things inside the function (other than using different data types), then you should use a template function. Otherwise you'll be copying & pasting functions and only changing data types.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,640
    Technically, a template function is a means of creating a set of overloaded functions.

    As a rule of thumb, I will employ template functions if I need an overloaded function that works for many argument types and, if I was to implement every possible version of that function by hand, the body for most of those versions would be essentially the same.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 09:18 PM
  2. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 04:33 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 10:51 AM

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