问题描述
在我的代码中,我重载了 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;}
和使用 Catch2 的 test.cpp
使用此类
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
与 std::cout
一起使用,则效果很好
INFO(frame); // <== Compiler error
std::cout << frame << '\n'; // <== OK
所以我认为,编译器可以正确解析运算符。我还尝试更改包含文件的顺序和干净的重建 - 没有成功。
有什么想法吗?谢谢
解决方法
@Meowmere:是的,您的 suggested answer 解决了问题 - 谢谢
解决方案是使用派生类而不是别名。
using ByteArray_t = std::vector<uint8_t>; // does **NOT** work
struct ByteArray_t :public std::vector<uint8_t> {}; // works