When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std; How can I do this with a user-defined class [...]
std::sort
is a template not a function, but otherwise it is not different from code you can write yourself:
namespace foo {
void bar() {}
}
using namespace foo;
int main() {
bar(); // ok
}
This works for namespaces but not for members of classes (there is using
for members of classes to bring something from a base class scope into the derived class scope, but thats a different topic and beyond the scope of the question (no pun intended), it is not what you are asking for here).
In your example there is no reason why foo
should be a member of A
, hence you should make it a free function (as above). Supposed you didn't write A
but you still need to call it without qualifiying the class name you can wrap it in a free function.
Also note that you are not allowed to add something to namespace std
. If you do, your code has undefined behavior.
And finally, note that there are good reasons to discourge usage of using some_namespace;
altogether. Consider this:
namespace foo1 {
void bar(){}
}
namespace foo2 {
void bar(){}
}
// lots of other code
using namespace foo1;
// lots of other code
int main() {
foo1::bar(); // this is bar from foo1
foo2::bar(); // this is bar from foo2
bar(); // to know which bar this is you have to
// look for any using directive, ie
// it makes your code much harder to read
}
Code is written once but read many times. The 6 extra characters to type pay off in more clear code. See also:
Why is “using namespace std;” considered bad practice?