加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使一个常量引用的元组?

发布时间:2020-12-16 05:52:41 所属栏目:百科 来源:网络整理
导读:说有两个功能: void ff( const std::tupleconst int ) { }template typename TT void gg( const std::tupleconst TT ) { } 并呼吁这些功能: int xx = 0;ff( std::tie( xx ) ); // passesgg( std::tie( xx ) ); // FAILS !! GCC 4.7.2无法编译最后一行并报
说有两个功能:
void ff( const std::tuple<const int&> ) { }

template < typename TT >
void gg( const std::tuple<const TT&> ) { }

并呼吁这些功能:

int xx = 0;
ff( std::tie( xx ) ); // passes
gg( std::tie( xx ) ); // FAILS !!

GCC 4.7.2无法编译最后一行并报告错误信息,如:

note:   template argument deduction/substitution failed:
note:   types ‘const TT’ and ‘int’ have incompatible cv-qualifiers
note:   ‘std::tuple<int&>’ is not derived from ‘std::tuple<const TT&>’

第一个问题是,如果这符合C11标准,如果没有,那为什么?

此外,为了克服这个问题,需要将一个const引用元组传递给gg,而不是传递一个非const引用的元组(其中std :: tie使得).这可以通过以下方式完成:

gg( std::tie( std::cref(x) ) );

然而,额外调用std :: cref是一种乏味的东西,所以有一些像ctie这样会产生一个常量引用的元组是非常好的.

第二个问题是如果有必要手动写ctie,如果是的话,那么这是最好的办法吗?

template < typename... T >
std::tuple<const T&...> ctie( const T&... args )
{
    return std::tie( args... );
}

解决方法

The first question is if this fits with the C++11 standard,and if it doesn’t,then why?

这是预期的行为.在第二种情况下,模板参数推导失败,因为没有T,因此元组< const T&>变为元组< int&>.

在第一种情况下,它的作用是因为元组< int&>可隐式转换为元组< const int&>.这是一个用户定义的转换,因此在模板参数推导过程中不被考虑.

你的问题有点像X / Y问题.考虑发布真正的问题,让您寻找涉及这种功能模板/元组合的解决方案.

您的ctie功能模板看起来不错.但请记住,像

auto t = ctie(5);

基本上会产生悬挂的参考.因此,您可能只想将ctie限制为lvalues.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读