Thread: Amperstand in template func.

  1. #1
    Registered User
    Join Date
    Sep 2004

    Unhappy Amperstand in template func.


    A simple quick question here....

    In the following template function, whats the purpose of the '&' in the argument of the BridgeIt function? I tried running it without the '&' and got the exact same output!

    #include <stdio.h>

    template <class T>
    int BridgeIt (T& t1) {
    return t1+1;

    int main() {
    int a = 3;
    printf("A: %d\n", BridgeIt(a));

    return 0;


  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Northern Virginia/Washington DC Metropolitan Area
    It means that the t1 argument is a reference. It all deals with different ways to pass values into function. Look here and check out the section on references midway down the page.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jun 2004
    Consider thise code:

    #include <string>
    #include <cstdio>
    class X
        std::string s;
        int x;
        X () {
            s = "a really long string";
            x = 10;
        int operator+(int y)
            return x + y;
    template<class T>
    int BridgeIt(T& t1)
        return t1 + 1;
    int main()
        X x;
        std::printf("%d\n", BridgeIt(x));
      return 0;
    Here we have a class with an int and a string member. The string is very long and copying takes a long time.
    The parameter in BridgeIt can have all types, from int and double to complete objects. If the parameters was by value (without &) you can run into performance problems easily because the parameter passed in is copied instead of passed by reference. So, to keep the code as generic as possible it is better to have the template take arguments by reference.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. error: template with C linkage
    By michaels-r in forum C++ Programming
    Replies: 3
    Last Post: 05-17-2006, 08:11 AM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM