简体   繁体   English

C ++中的模板参数

[英]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). 假设我有任意模板方法,它可以通过值const引用接收参数(显然,对于普通类型和相应的对象)。

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? 我可以在这里做些更聪明的东西吗?

只需使用const引用ALWAYS,因为将原始类型作为const引用传递没有太多开销。

仅为const引用编写模板代码,并依赖编译器来优化引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM