什么时候使用std :: ref必不可少? [英] When is the use of std::ref necessary?

查看:150
本文介绍了什么时候使用std :: ref必不可少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑:

  std :: tuple< int,const A& func(const A& a)
{
return std :: make_tuple(0,std :: ref(a));
}

std :: ref 需要编写正确和可移植的代码?



如果我删除 std:

:ref 我的代码构建正常,没有任何警告( g ++ - 4.6 -Wall ),但不能正确运行。



如果感兴趣, A 的定义:

  struct A {
std :: array< int,2> vec;
typedef int type_t;

template< typename ... OPs,typename ... VALs>
A& operator =(const std :: pair< std :: tuple< VALs ...>,std :: tuple< OPs ...>& e){
for(int i = i vec [i] = eval(extract(i,e.first),e.second);
}
}
};


解决方案


  • make_tuple(0,a)使 tuple

  • make_tuple(0,ref(a))使得 tuple
  • 您也可以说 tuple< int,A&> make_tuple ,或者使用 std :: tie(){t(0,a);


Consider:

std::tuple<int , const A&> func (const A& a) 
{
  return std::make_tuple( 0 , std::ref(a) );
}

Is the std::ref required for writing correct and portable code? (It compiles fine without it)

Background:

If I remove std::ref my code builds fine without any warnings (g++-4.6 -Wall), but doesn't run correctly.

In case of interest the definition of A:

struct A {
  std::array<int,2> vec;
  typedef int type_t;

  template<typename... OPs,typename... VALs>
  A& operator=(const std::pair< std::tuple<VALs...> , std::tuple<OPs...> >& e) {
    for( int i = 0 ; i < vec.size() ; ++i ) {
      vec[i] = eval( extract(i,e.first) , e.second );
    }
  }
};

解决方案

  • make_tuple(0, a) makes a tuple<int, A>.
  • make_tuple(0, ref(a)) makes a tuple<int, reference_wrapper<A>>.
  • You can also say tuple<int, A&> t(0, a); for a tuple you can't make with make_tuple, or use std::tie.

这篇关于什么时候使用std :: ref必不可少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆