Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template parameters in C++

Suppose I have arbitrary template method, which could receive parameters by value and by const reference (obviously, for trivial types and for objects accordingly).

How is this situation handled when writing template function prototypes?

I could make something like:

template <typename T> void Foo(T value) {
   // Do something.
}

template <typename T> void Foo(const T& value) {
   // Do something, yeah.
}

// Specialization for first prototype. 
template <> void Foo<int>(int value) { }

// Specialization for second prototype. 
template <> void Foo<Object>(const Object& value) { }

But this approach is only okay for trivial functions, that act purely as a wrapper for some other calls.

If the function (non-templated version) has a lot of code inside it, this means I would have to copy the code twice.

Can I make something smarter here?

like image 202
Yippie-Ki-Yay Avatar asked Feb 16 '26 11:02

Yippie-Ki-Yay


2 Answers

Just take by const reference ALWAYS, because there isn't much overhead in passing primitive types as const references.

like image 77
Armen Tsirunyan Avatar answered Feb 17 '26 23:02

Armen Tsirunyan


Write your template code for const references only and rely on the compiler to optimize the references away.

like image 20
Fred Foo Avatar answered Feb 18 '26 00:02

Fred Foo