在编写测试套件时,我需要为Boost单元测试提供operator<<(std::ostream&...
的实现。
这段代码有效:
namespace theseus { namespace core {
std::ostream& operator<<(std::ostream& ss, const PixelRGB& p) {
return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")");
}
}}
这个没有:
std::ostream& operator<<(std::ostream& ss, const theseus::core::PixelRGB& p) {
return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")");
}
显然,当g++试图解析操作符的使用时,第二个并没有包含在候选匹配中。为什么会这样(是什么规则导致了这种情况)?
调用operator<<
的代码深入到了Boost单元测试框架中,但以下是测试代码:
BOOST_AUTO_TEST_SUITE(core_image)
BOOST_AUTO_TEST_CASE(test_output) {
using namespace theseus::core;
BOOST_TEST_MESSAGE(PixelRGB(5,5,5)); // only compiles with operator<< definition inside theseus::core
std::cout << PixelRGB(5,5,5) << "\n"; // works with either definition
BOOST_CHECK(true); // prevent no-assertion error
}
BOOST_AUTO_TEST_SUITE_END()
供参考,我正在使用g++ 4.4(虽然目前我假设这种行为符合标准)。
operator<<
? - CB Bailey