Thread: Question about Templates and passing arguments

  1. #1
    Registered User
    Join Date
    Sep 2002

    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:

    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
    Waterloo, Texas
    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.
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    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, 12:18 PM
  3. passing templates as parameters - something funky?
    By archetype in forum C++ Programming
    Replies: 1
    Last Post: 02-20-2002, 08:38 PM