【问题标题】:Is it possible to write two template functions as one when the only difference is the const-ness of an argument?当唯一的区别是参数的常量时,是否可以将两个模板函数编写为一个?
【发布时间】:2015-05-05 20:12:45
【问题描述】:

我有类似的东西:

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); }

一些Foobs 采用const T&amp;s 而另一些Foobs 采用T&amp;s,或者相同的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); }

【问题讨论】:

  • @Columbo:不确定我是否理解您的评论,我说的显然行不通,这里是证明:ideone.com/t1GS5P
  • 哎呀,我不小心跳过了T。 :) 如果删除它(以及相应的参数声明),您将得到如下所示的解决方案。

标签: c++ templates constants


【解决方案1】:

实际上,如果t 参数始终是左值,那么您只需要第一个重载!如果左值的类型为const U,则模板参数T推导出为const U,实例化函数的第二个参数类型为const U&amp;,它可以很好地绑定到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)); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2021-12-21
    • 2017-02-28
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多