C++ operator lookup rules / Koenig lookup

Posted by John Bartholomew on Stack Overflow See other posts from Stack Overflow or by John Bartholomew
Published on 2011-01-05T12:16:22Z Indexed on 2011/01/05 13:54 UTC
Read the original article Hit count: 268

While writing a test suite, I needed to provide an implementation of operator<<(std::ostream&... for Boost unit test to use.

This worked:

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 << ")");
    }
}}

This didn't:

std::ostream& operator<<(std::ostream& ss, const theseus::core::PixelRGB& p) {
    return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")");
}

Apparently, the second wasn't included in the candidate matches when g++ tried to resolve the use of the operator. Why (what rule causes this)?

The code calling operator<< is deep within the Boost unit test framework, but here's the test code:

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()

For reference, I'm using g++ 4.4 (though for the moment I'm assuming this behaviour is standards-conformant).

© Stack Overflow or respective owner

Related posts about c++

Related posts about argument-dependent-lookup