Question about Templates and passing arguments

This is a discussion on Question about Templates and passing arguments within the C++ Programming forums, part of the General Programming Boards category; Hello all, I am currently taking a Data Structures course and we are discussing the topic of templates and its ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    92

    Question about Templates and passing arguments

    Hello all,
    I am currently taking a Data Structures course and we are discussing the topic of templates and its remifications in the world of generic programming. I had a few questions if anyone would like to answer them.
    I present to you the swap function as a generic algorithm:

    Code:
    template <typename T>
    void swap (T& t1, &T t2)
    {
        T temp;
        temp = t1;
        t1 = t2;
        t2 = temp;
    }
    My question is regarding the arguments for this template function. Why are they being passed in like this? Any advantages or disadvantages to this way of argument passing? Thank you.

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,659
    I am assuming you are referring to passing a reference? The advantages are:

    You can change the object, just as if you had passed a pointer.
    You can use non-pointer syntax.
    A reference will always be non-null.



    ITSA
    Socket Library!

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Also, the biggest advantage at times is the the reference is usually quiker to pass than the whole object (like a pointer)

    So if your object is 40bytes, its easier to pass a 4 byte reference

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Template values on to other classes
    By vinsta18 in forum C++ Programming
    Replies: 5
    Last Post: 10-20-2004, 05:26 PM
  2. Stack Question With Templates
    By Anonymous Freak in forum C++ Programming
    Replies: 6
    Last Post: 02-09-2003, 11:18 AM
  3. passing templates as parameters - something funky?
    By archetype in forum C++ Programming
    Replies: 1
    Last Post: 02-20-2002, 07:38 PM

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