diff --git a/src/base/bitunion.hh b/src/base/bitunion.hh index 569d65031f..b2a2ba806d 100644 --- a/src/base/bitunion.hh +++ b/src/base/bitunion.hh @@ -32,7 +32,9 @@ #define __BASE_BITUNION_HH__ #include +#include #include +#include #include "base/bitfield.hh" @@ -414,4 +416,48 @@ namespace std }; } + +namespace BitfieldBackend +{ +namespace +{ + template + std::ostream & + bitfieldBackendPrinter(std::ostream &os, const T &t) + { + os << t; + return os; + } + + //Since BitUnions are generally numerical values and not character codes, + //these specializations attempt to ensure that they get cast to integers + //of the appropriate type before printing. + template <> + std::ostream & + bitfieldBackendPrinter(std::ostream &os, const char &t) + { + os << (const int)t; + return os; + } + + template <> + std::ostream & + bitfieldBackendPrinter(std::ostream &os, const unsigned char &t) + { + os << (const unsigned int)t; + return os; + } +} +} + +//A default << operator which casts a bitunion to its underlying type and +//passes it to BitfieldBackend::bitfieldBackendPrinter. +template +std::ostream & +operator << (std::ostream &os, const BitUnionType &bu) +{ + return BitfieldBackend::bitfieldBackendPrinter( + os, (BitUnionBaseType)bu); +} + #endif // __BASE_BITUNION_HH__ diff --git a/src/base/bituniontest.cc b/src/base/bituniontest.cc index 8781d2d5ec..d7ed95bb87 100644 --- a/src/base/bituniontest.cc +++ b/src/base/bituniontest.cc @@ -270,3 +270,17 @@ TEST_F(BitUnionData, Templating) is64 = std::is_same, uint64_t>::value; EXPECT_FALSE(is64); } + +TEST_F(BitUnionData, Output) +{ + sixtyFour = 1234567812345678; + std::stringstream ss; + ss << sixtyFour; + EXPECT_EQ(ss.str(), "1234567812345678"); + ss.str(""); + + EmptyEight eight = 65; + ss << eight; + EXPECT_EQ(ss.str(), "65"); + ss.str(""); +}