首页 > 解决方案 > Catch2:将类移动到命名空间后,INFO 无法识别重载流运算符

问题描述

在我的代码中,我为 ByteArray 类重载了流运算符(它只是一个字节向量)。

// myfile.hpp
using ByteArray_t = std::vector<uint8_t>;

std::ostream &operator<<(std::ostream &os, const ByteArray_t &array);
...

// myfile.cpp
std::ostream &operator<<(std::ostream &os, const ByteArray_t &array) {... return os;}

和一个test.cpp使用这个类的使用 Catch2

TEST_CASE("Oh-my", "[...]") {
  ByteArray_t frame = create(max_val); // write the bytes of max val into the array

  INFO(frame); // Print frame if test fails (uses '<<' operator)

  REQUIRE(...);
}

除非我引入了命名空间,否则这很好用


namespace mw {
// myfile.hpp
using ByteArray_t = std::vector<uint8_t>;

std::ostream &operator<<(std::ostream &os, const ByteArray_t &array);
} // namespace mw
...

// myfile.cpp
namespace mw {
std::ostream &operator<<(std::ostream &os, const ByteArray_t &array) {... return os;}
}  // namespace mw

现在编译器抱怨

 error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const std::vector<unsigned char, std::allocator<unsigned char> >')
            *m_oss << value;
            ~~~~~~ ^  ~~~~~
.../include/catch2/catch.hpp:2629:22: note: in instantiation of function template specialization 'Catch::ReusableStringStream::operator<<<std::vector<unsigned char, std::allocator<unsigned char> > >' requested here
            m_stream << value;
tests.cpp:69:15: note: in instantiation of function template specialization 'Catch::MessageBuilder::operator<<<std::vector<unsigned char, std::allocator<unsigned char> > >' requested here
  **INFO(frame);**

但是,如果我使用framewith std::cout,这很好用

  INFO(frame);                // <== Compiler error
  std::cout << frame << '\n'; // <== OK

所以我认为,编译器可以正确解析运算符。我还尝试更改包含文件的顺序并进行干净的重建 - 没有成功。

有任何想法吗?谢谢

标签: c++operator-overloadingcatch2

解决方案


@Meowmere:是的,您建议的答案解决了问题-谢谢

解决方案是使用派生类而不是别名。

using ByteArray_t = std::vector<uint8_t>; // does **NOT** work
struct ByteArray_t :public std::vector<uint8_t> {}; // works

推荐阅读