Using a template function in an anonymous namespace

1

I am trying to use Strong Types and to add stream operator for them.

In my source file I put all of these helpers in an anonymous namespace. One of these helpers is using a template stream operator (utils::to_hex(T)) defined in another header.

namespace { // Anonymous namespace

// Example custom strong type
using custom_type = utils::StrongType<std::uint32_t, struct Custom>;

// Stream operator for custom type
std::ostream &operator<<(std::ostream &_os, const custom_type &_value)
{
    return (_os << utils::to_hex(static_cast<std::uint32_t>(_value)));
}

}

int main(void)
{
    custom_type c = 0xDEADBEEF;

    std::cout << c << std::endl;
}

The whole code: http://cpp.sh/2ln7q

I cannot compile this code. I am stuck with:

test.cc: In function ‘std::ostream& {anonymous}::operator<<(std::ostream&, const custom_type&)’:
test.cc:72:14: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘utils::ToHex<unsigned int>’)
  return (_os << utils::to_hex(static_cast<std::uint32_t>(_value)));

Using the cpp.sh compiler I got:

 In function 'std::ostream& {anonymous}::operator<<(std::ostream&, const custom_type&)':
73:65: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/istream:39:0,
                 from /usr/include/c++/4.9/sstream:38,
                 from /usr/include/c++/4.9/iomanip:45,
                 from 3:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = utils::ToHex<unsigned int>]'
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

When I remove the anonymous namespace of if I use the static keyword everything is fine.

c++
c++11
asked on Stack Overflow Nov 21, 2018 by jml

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0