29262

Can you use boost::reference_wrapper to store references in an STL container?

Question:

I am trying to do this: maitain two vectors of strings whereby one vector stores values and the second stores references of the same values. I thought using boost::reference_wrapper would do the trick but it seems it won't. My platform is 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); }

This is the error:

<blockquote>

error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from std::basic_string<_Elem,_Traits,_Ax>' to 'const boost::reference

</blockquote>

I could use boost::shared_ptr but I thought a reference better expresses my intent. This code can probably work in C++11 using std::reference_wrapper but that is not available to me right now.

Answer1:

Yes, it can. The documentation states that it is CopyConstructible and Assignable which are required concepts for container template arguments. But you need to use boost::ref or boost::cref to create objects of type reference_wrapper. There is no implicit conversion and this is why your code does not work.

Be aware that a slight difference between std::reference_wrapper and boost::reference_wrapper is that only the std version works with functors.

Example:

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

If you dislike that and would like to have implicit conversion from the original value, you might want to use:

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

Although I would not do that.

Recommend

  • Use UIElements as ItemsSource of ListBox in Silverlight
  • Find method in std::wstring
  • mysql - query for thread list of messages with specific conditions
  • Cannot understand how to add new object to std::list
  • Compare Value with Comma Separated String SQL PHP
  • errors with multimap (key type is std::string)
  • Problems with STL as a static volatile member
  • passing a HANDLE variable to an unmanaged .dll in C++/CLI
  • cannot convert parameter 5 from 'SIZE_T *' to 'size_t *' — why?
  • Rascal ambiguity not resolved by disambiguation rules
  • CALLBACK macro (QT)
  • JXA Move a message to a different folder/mailbox
  • Can you put a pimpl-Class inside a vector
  • java.lang.NullPointerException: No FileItemFactory has been set
  • Why can't the compiler deduce template parameter from return type?
  • check if numbers have the same sign
  • Get row for each user where the count of a value in a column is maximum
  • Sorting a HashMap, while keeping duplicates
  • Thrust filter by key value
  • Load 24 bit TGA
  • Pointer vs Reference difference when passing Eigen objects as arguments
  • Replace and retrieve placeholder value
  • Simplify where clause with repeated associated type restrictions
  • Result showing lining on image
  • why my app based on boost::asio didn't accept new connection
  • Getting error java.io.FileNotFoundException (log4j log file) at the time of publish project on cloud
  • Opaque reference instead of PImpl. Is it possible?
  • runtime-check whether an instance (Base*) override a parent function (Base::f())
  • Delphi: Where is the shortcut that started the application? [duplicate]
  • Is there a parser equivalent of 'fragment' marking in ANTLR4?
  • How do I mock an exported typescript function in a jasmine test?
  • Setting the run time properties on SpringApplicationBuilder()
  • Invalid Date on validation Date of js
  • C: Incompatible pointer type initializing
  • AES padding and writing the ciphertext to a disk file
  • VS2008 Enable C++ Exception with SEH
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass