在匿名名称空间中使用模板函数

时间:2018-11-21 14:10:37

标签: c++ c++11

我正在尝试使用Strong Types并为其添加流操作符。

在我的源文件中,我将所有这些帮助器都放置在一个匿名名称空间中。这些助手之一就是使用在另一个标头中定义的模板流运算符(utils::to_hex(T))。

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

整个代码:http://cpp.sh/2ln7q

我无法编译此代码。我坚持:

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

使用cpp.sh编译器:

 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)

当我删除匿名命名空间时,如果我使用static关键字,一切都很好。

0 个答案:

没有答案
相关问题