Thread: template swap

  1. #1
    Unregistered
    Guest

    template swap

    Can someone please take a look at this futile attempt of mine at writting a function template for a function swap its 2 parameters. Also, in order for swap to do its designated task, do I have to pass the two objects by reference? Do both the templates do the same thing? Or did I go overboard on the first one?

    Thank you,
    Laina

    template 1
    template <class DataType>
    void swap(DataType & a, DataType & b)
    {
    DataType temp = a;
    a = b;
    b = temp;
    }

    void swap(float & a, float & b)
    {
    int temp = a;
    a = floor(b + .5); //rounds to the nearest integer
    b = floor(temp + .5); //rounds to the nearest integer
    }

    template <class DataType>
    void swap(DataType & a, DataType & b, DataType & c)
    {
    DataType temp = a;
    a = b;
    b = c;
    c = temp;
    }



    template 2
    template <typename t>
    void swap(t& A, t& B) {
    t T(A);
    A = B;
    B = T;
    }

  2. #2
    Unregistered
    Guest

    overload

    Do I have to overload a function or operator by an object in order to use this function?

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Those templates should work for any class that has a copy constructor and an assignment operator defined.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    void swap(float & a, float & b)
    {
    int temp = a;
    a = floor(b + .5); //rounds to the nearest integer
    b = floor(temp + .5); //rounds to the nearest integer
    }

    small mistake..... temp should be a float.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

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