接受const和非const的模板函数 [英] template function that accepts const and non-const
问题描述
有没有办法制作一个单独的模板函数,可以通过引用接受
const和非const参数类型,而无需制作
副本?
例如,我可以写这个将接受这两个,但总是
复制:
模板< typename T1>
无效接受(T1 t);
感谢您的时间。
Is there a way to make a single template function that will accept
both const and non-const parameter types by reference without making a
copy?
For example, I can write this which will accept both, but will always
make a copy:
template<typename T1>
void accept(T1 t);
Thanks for your time.
推荐答案
u.int.32.t写道:
u.int.32.t wrote:
有没有办法制作一个接受
引用const和非const参数类型而没有制作
副本?
例如,我可以写这个接受这两个,但总是
复制:
模板< typename T1>
void accept(T1 t);
感谢您的时间。
Is there a way to make a single template function that will accept
both const and non-const parameter types by reference without making a
copy?
For example, I can write this which will accept both, but will always
make a copy:
template<typename T1>
void accept(T1 t);
Thanks for your time.
使用参考:
模板< typename T1>
void accept(T1& t);
Use a reference:
template<typename T1>
void accept(T1& t);
4月22日上午10点23分,Rolf Magnus< ramag ... @ t-online.dewrote:
On Apr 22, 10:23 am, Rolf Magnus <ramag...@t-online.dewrote:
u.int.32.t写道:
u.int.32.t wrote:
有没有办法让一个模板函数接受
引用const和非const参数类型而没有制作
副本?
Is there a way to make a single template function that will accept
both const and non-const parameter types by reference without making a
copy?
例如,我可以写这个将接受这两个,但总是
复制:
For example, I can write this which will accept both, but will always
make a copy:
template< typename T1>
void accept(T1 t);
template<typename T1>
void accept(T1 t);
感谢您的时间。
Thanks for your time.
使用参考:
模板< typename T1>
void accept(T1&吨);
Use a reference:
template<typename T1>
void accept(T1& t);
是的,但是如果接受被称为:这不会有效:
accept(5);
例如。
Yes but this won''t work if accept is called as:
accept(5);
For example.
u.int.32.t写道:
u.int.32.t wrote:
有没有办法制作一个单独的模板函数,可以通过引用接受
const和非const参数类型,而无需制作
副本?
例如,我可以写这个同时接受这两个,但总是
复制一份:
模板< typename T1>
无效接受(T1 t);
感谢您的时间。
Is there a way to make a single template function that will accept
both const and non-const parameter types by reference without making a
copy?
For example, I can write this which will accept both, but will always
make a copy:
template<typename T1>
void accept(T1 t);
Thanks for your time.
你为什么要这样?如果你想通过引用接受const和非const
参数,该函数不能修改它们。所以只需使用
模板< typename T1>
void accept(const T1& t);
-
Ian Collins。
Why would you want to? If you want to accept both const and non-const
parameters by reference, the function can''t modify them. So just use
template <typename T1>
void accept(const T1& t);
--
Ian Collins.
这篇关于接受const和非const的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!