Opened 8 years ago
Closed 8 years ago
#10825 closed Bugs (fixed)
Undefined stream insertion operator in boost::optional .
Reported by: | Owned by: | akrzemi1 | |
---|---|---|---|
Milestone: | Boost 1.58.0 | Component: | optional |
Version: | Boost 1.56.0 | Severity: | Problem |
Keywords: | undefined stream insertion operator | Cc: | kumaram@… |
Description
I get undefined reference error while using boost::optional. Following code can be used to reproduce the error:
#include <iostream> #include <boost/optional.hpp> void print_optional(int type) { boost::optional<int> value; if (type == 1) { value = boost::optional<int>(1000); } std::cout << value; } int main() { print_optional(1); } test_opt.cpp:(.text+0x64): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& boost::operator<< <char, std::char_traits<char>, int>(std::basic_ostream<char, std::char_traits<char> >&, boost::optional<int> const&)' collect2: error: ld returned 1 exit status
We are getting this because starting boost-1.56, stream insertion operator is declared in optional.hpp but not defined:
// Forward declaration to prevent operator safe-bool from being used. template<class CharType, class CharTrait, class T> std::basic_ostream<CharType, CharTrait>& operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v); // There is no definition of this function.
Possible Solution
Adding following code fixed this issue for me:
namespace boost { template<class CharType, class CharTrait, class T> std::basic_ostream<CharType, CharTrait>& operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v) { if (v) { out << *v; } return out; } }
Change History (5)
comment:1 by , 8 years ago
comment:2 by , 8 years ago
Why you don't include
#include <boost/optional/optional_io.hpp>
if you want to print an optional?
comment:3 by , 8 years ago
Milestone: | To Be Determined → Boost 1.58.0 |
---|---|
Owner: | changed from | to
Status: | new → assigned |
comment:4 by , 8 years ago
In order to stream out optional objects you have to include the IO header:
#include <boost/optional/optional_io.hpp>
I changed the implementation a bit, so that rather than a link-time error you get a compile time error about missing header. The change is now in develop branch.
comment:5 by , 8 years ago
Resolution: | → fixed |
---|---|
Status: | assigned → closed |
related bug https://svn.boost.org/trac/boost/ticket/2103
rolling back changes from #2103 fixes this one.