在我的代码中,我为 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);**
但是,如果我使用frame
with std::cout
,这很好用
INFO(frame); // <== Compiler error
std::cout << frame << '\n'; // <== OK
所以我认为,编译器可以正确解析运算符。我还尝试更改包含文件的顺序并进行干净的重建 - 没有成功。
有任何想法吗?谢谢