C++ 中的模板参数
假设我有任意模板方法,它可以按值和按常量引用接收参数(显然,对于简单类型和相应的对象)。
编写模板函数原型时如何处理这种情况?
我可以做这样的事情:
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) { }
但这种方法只适用于简单的函数,它纯粹充当其他一些调用的包装器。
如果函数(非模板化版本)内部有很多代码,这意味着我必须将代码复制两次。
我可以吗让这里变得更聪明?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
始终使用 const 引用,因为将基本类型作为 const 引用传递并没有太多开销。
Just take by const reference ALWAYS, because there isn't much overhead in passing primitive types as const references.
仅针对
const
引用编写模板代码,并依靠编译器来优化引用。Write your template code for
const
references only and rely on the compiler to optimize the references away.