【问题标题】:Can you use boost::reference_wrapper to store references in an STL container?您可以使用 boost::reference_wrapper 将引用存储在 STL 容器中吗?
【发布时间】:2012-04-22 20:51:43
【问题描述】:

我正在尝试这样做:维护两个字符串向量,其中一个向量存储值,第二个存储相同值的引用。我认为使用boost::reference_wrapper 可以解决问题,但似乎不会。我的平台是 Visual C++ 2008。

std::vector<std::string> str_vec;
str_vec.push_back("abc");
str_vec.push_back("cde");
str_vec.push_back("fgh");

std::vector<boost::reference_wrapper<std::string> > str_view;
for(std::vector<std::string>::iterator it = str_vec.begin(); it != str_vec.end(); ++it)
{
  str_view.push_back(*it);
}

这是错误:

错误 C2664: 'std::vector<_ty>::push_back' : 无法将参数 1 从 std::basic_string<_elem>' 转换为 'const boost::reference

我可以使用boost::shared_ptr,但我认为引用可以更好地表达我的意图。这段代码可能可以使用std::reference_wrapper 在 C++11 中工作,但我现在无法使用。

【问题讨论】:

  • 什么是visual c++ 2009?据我所知,有 2008、2010 和 2011 测试版。

标签: c++ boost


【解决方案1】:

是的,可以。文档指出 CopyConstructibleAssignable 是容器模板参数的必需概念。但是您需要使用boost::refboost::cref 来创建reference_wrapper 类型的对象。没有隐式转换,这就是您的代码不起作用的原因。

请注意,std::reference_wrapperboost::reference_wrapper 之间的细微差别是只有 std 版本适用于函子。

例子:

std::vector<std::string> str_vec;
str_vec.push_back("abc");
str_vec.push_back("cde");
str_vec.push_back("fgh");

std::vector<boost::reference_wrapper<std::string> > str_view;
std::transform(begin(str_vec), end(str_vec),
               std::back_inserter(str_view), boost::ref<std::string>);

如果您不喜欢这样并希望从原始值进行隐式转换,您可能需要使用:

template<typename T>
class my_ref_wrap : public boost::reference_wrapper<T> {
public:
  my_ref_wrap(T& t) : boost::reference_wrapper<T>(t) {}
};

std::vector<my_ref_wrap<std::string> > str_view;
std::copy(begin(str_vec), begin(str_vec),
          std::back_inserter(str_view));

虽然我不会那样做。

【讨论】:

  • 您介意在 C++03 中举个例子吗?我没有 c++11 编译器
  • @user841550 这基本上是 C++03。您只需将begin(str_vec) 更改为str_vec.begin()end() 也是如此。
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2020-05-18
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
相关资源
最近更新 更多