Thread: Problem writing swap using pointers

  1. #1
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146

    Problem writing swap using pointers

    The assignment is simple: Write a function template with the following declaration:
    Code:
    template <class S>
    void swap( S *a, S *b );
    So, I wrote the easy little function like so:
    Code:
    template <class S>
    void swap( S *a, S *b )
    {
      S temp = *a;
      *a = *b;
      *b = temp;
    }
    The problem is when I try to call it like so:
    Code:
    int a=1, b=2;
    swap(a, b);
    The compiler says that there's no matching function, swap(int&, int&). I did get the function to work if I called it like this:
    Code:
    swap(&a, &b);
    That makes sense, I suppose, but it seems very inconveinent. I'm used to passing the arguments as reference parameters and then just calling it like swap(a, b).

    Do I need to call the assigned function as swap(&a, &b) all the time, or is there something else I'm missing?
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  2. #2
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    well, your function is asking for a pointer, so logically, you would have to pass a pointer and not be able to just pass a straight int value.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File Writing Problem
    By polskash in forum C Programming
    Replies: 3
    Last Post: 02-13-2009, 10:47 AM
  2. Problem with pointers
    By jcafaro10 in forum C++ Programming
    Replies: 4
    Last Post: 01-27-2009, 02:36 PM
  3. Problem with Vectors And Pointers
    By Shamino in forum Game Programming
    Replies: 3
    Last Post: 01-21-2006, 07:23 PM
  4. problem writing a string container class
    By *ClownPimp* in forum C++ Programming
    Replies: 2
    Last Post: 06-09-2002, 06:55 PM
  5. problem , need pointers. thanks
    By mobius in forum C Programming
    Replies: 4
    Last Post: 09-03-2001, 05:12 AM