Использование функции шаблона в анонимном пространстве имен - PullRequest
0 голосов
/ 21 ноября 2018

Я пытаюсь использовать Сильные типы и добавить для них оператор потока.

В своем исходном файле я поместил все эти помощники в анонимное пространство имен.Один из этих помощников использует оператор потока шаблонов (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 ключевое слово все нормально.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...