【发布时间】:2011-01-05 12:16:22
【问题描述】:
在编写测试套件时,我需要提供 operator<<(std::ostream&... 的实现以供 Boost 单元测试使用。
这行得通:
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<<的范围是什么? -
@Charles:我已经编辑添加了测试代码。
标签: c++ argument-dependent-lookup