当唯一的区别是参数的常量性时,是否可以将两个模板函数写成一个?

Is it possible to write two template functions as one when the only difference is the const-ness of an argument?

我有类似的东西:

template <class Foob, class T>
void do_it(Foob& f, T& t) { f.proc(t); }

template <class Foob, class T>
void do_it(Foob& f, const T& t) { f.proc(t); }

有些 Foob 需要 const T& 秒,而其他 Foob 只需要 T& 秒,或者相同的 Foob 甚至可能有两个 procs,一种用于 const 情况,一种用于非 const 情况,它们做不同的事情。

然而,do_it 的代码是相同的:只是 f.proc(t)。有时代码很多行,但仍然相同。有没有办法把 do_it 写成一个函数?像这样的东西,虽然这显然行不通:

template <class Foob, class MaybeConst, class T>
void do_it(Foob& f, MaybeConst T& t) { f.proc(t); }

实际上,如果 t 参数始终是左值,那么您只需要第一个重载!如果左值的类型为 const U,则模板参数 T 被推导出为 const U 并且实例化函数的第二个参数类型将为 const U&,它将绑定到 const 左值就好了。

仅当参数是右值时才需要第二个重载。但与其将其作为特例,不如使用完美转发?

// works for both lvalues and rvalues with any cv-qualification
template <class Foob, class T>
void do_it(Foob& f, T&& t) { f.proc(std::forward<T>(t)); }