When writing non-member, free functions, can they be placed in the global namespace so long as the signature specifies a namespace-scoped object? For example, in the code below, is "Example 2" acceptable design? Which is better, Example 1 or Example 2? Does your answer change if the function is an operator overload?
Research: I don't think this question was addressed when I took a C++ programming class (or it may have been addressed before I was ready to understand it). I tried searching for the answer with a few different permutations of the keywords but did not get any quality hits.
#include <iostream>
#include <string>
#include <sstream>
/* Example 1 */
namespace myapp
{
namespace xyz
{
class Thing
{
public:
Thing( int value ) : myValue( value ) {}
void setValue( int value ) { myValue = value; }
int getValue() const { return myValue; }
private:
int myValue;
};
std::string toString( const Thing& thing )
{
std::stringstream ss;
ss << thing.getValue();
return ss.str();
}
}
}
/* Example 2 */
namespace myapp
{
namespace xyz
{
class AnotherThing
{
public:
AnotherThing( int value ) : myValue( value ) {}
void setValue( int value ) { myValue = value; }
int getValue() const { return myValue; }
private:
int myValue;
};
}
}
std::string toString( const myapp::xyz::AnotherThing& thing )
{
std::stringstream ss;
ss << thing.getValue();
return ss.str();
}
int main(int argc, const char * argv[])
{
/* Example 1 */
myapp::xyz::Thing t( 1 );
std::cout << myapp::xyz::toString( t ) << std::endl;
/* Example 2 */
myapp::xyz::AnotherThing a( 2 );
std::cout << toString( a ) << std::endl;
return 0;
}