www.digitalmars.com         C & C++   DMDScript  

c++.beta - namespace and friend operators

reply Richard Grant <fractal clark.net> writes:
Ran into this minor issue with an extraction operator. Unable to namespace
qualify the operator at global scope. And can't remove the namespace qualifier
since the first declaration is as a friend in namespace scope.

Easy to fix.. inject the operator definition into the namespace scope. 

When I tried other ways to fix.. such as declare the operator before the friend
declaration, I ran into ambiguous symbols for the operator that could not be
resolved by specifying the namespace scope operator as global (ala ::operator<<
in the Test class defined below).

I'm not really sure one would want the operator in the global namespace anyway,
and lookup rules find the operator based on the type of the operands.

namespace test {

class Test {
public:
Test() : i(10) { }
private:
int i;
friend std::ostream& operator<<(std::ostream& os, const Test& t);
};

} // test

std::ostream& test::operator<<(std::ostream& os, const Test& t) {
// Error: 'test' must be a class name preceding '::'
os << t.i;
return os;
}

int main() {
test::Test t;
std::cout << t << std::endl;
}

Richard
Feb 11 2003
parent %u <123 123.com> writes:
missing ';' of namespace
Sep 24 2009