template pass by const reference

Posted by 7vies on Stack Overflow See other posts from Stack Overflow or by 7vies
Published on 2011-02-02T15:04:53Z Indexed on 2011/02/02 15:26 UTC
Read the original article Hit count: 235

Hi, I've looked over a few similar questions, but I'm still confused. I'm trying to figure out how to explicitly (not by compiler optimization etc) and C++03-compatible avoid copying of an object when passing it to a template function. Here is my test code:

#include <iostream>

using namespace std;

struct C
{
  C() { cout << "C()" << endl;  }
  C(const C&) { cout << "C(C)" << endl; }
  ~C() { cout << "~C()" << endl;  }
};

template<class T> void f(T) { cout << "f<T>" << endl; }

template<> void f(C c) { cout << "f<C>" << endl; } // (1)

template<> void f(const C& c) { cout << "f<C&>" << endl; } // (2)

int main()
{
    C c;
    f(c);
    return 0;
}

(1) accepts the object of type C, and makes a copy. Here is the output:

C()
C(C)
f<C>
~C()
~C()

So I've tried to specialize with a const C& parameter (2) to avoid this, but this simply doesn't work (apparently the reason is explained in this question).

Well, I could "pass by pointer", but that's kind of ugly. So is there some trick that would allow to do that somehow nicely?

EDIT: Oh, probably I wasn't clear. I already have a templated function

template<class T> void f(T) {...}

But now I want to specialize this function to accept a const& to another object:

template<> void f(const SpecificObject&) {...}

But it only gets called if I define it as

template<> void f(SpecificObject) {...}

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates