c++ - 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);**
但是,如果我使用frame
with std::cout
,这很好用
INFO(frame); // <== Compiler error
std::cout << frame << '\n'; // <== OK
所以我认为,编译器可以正确解析运算符。我还尝试更改包含文件的顺序并进行干净的重建 - 没有成功。
有任何想法吗?谢谢
解决方案
@Meowmere:是的,您建议的答案解决了问题-谢谢
解决方案是使用派生类而不是别名。
using ByteArray_t = std::vector<uint8_t>; // does **NOT** work
struct ByteArray_t :public std::vector<uint8_t> {}; // works
推荐阅读
- c# - 在 Xamarin Forms 应用程序中获取 Android 联系人
- javascript - Windows 使用 e.clientX 移动得太快
- javascript - 如何根据从nodejs中的查询接收到的数据在新页面上呈现动态数量的卡片?
- javascript - 使用 React 将动态画布作为 div 的背景
- javascript - 类型错误:尝试使用本地存储而不是使用状态时无法读取未定义的属性“地图”
- access-token - 如何为谷歌服务帐户生成令牌
- regex - 是否有 Notepad++ RegEx 可以删除除数字和空格之外的所有内容?
- java - 离散余弦变换实现
- node.js - 反应脚本构建失败
- ruby - 如何连接到 dockerized Sinatra 应用程序