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?
Just take by const reference ALWAYS, because there isn't much overhead in passing primitive types as const references.
Write your template code for const references only and rely on the compiler to optimize the references away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With