Reputation: 34175
To keep class definition in header file clean, I decided to move implementations of templated functions into another *.h
file, which I include in the main header. Now I would like to make use of using namespace
there, to make code more readable.
But using namespaces would affect the whole application, since the file gets included in the header which itself gets included in the whole application. The using
of the namespaces would spread out of the file.
How can I handle this?
Upvotes: 1
Views: 894
Reputation: 17926
You can put using namespace XX
inside function definitions to scope the using declaration to that function:
int func( ...args... )
{
using namespace std;
// ... body of function
}
Upvotes: 4
Reputation: 1111
You can place the using namespace
in the namespace
of your 'main header':
Header.h
#include <string>
namespace Test
{
using namespace std;
string f()
{
return "Test";
};
}
main.cpp
#include "Header.h"
int main()
{
Test::f();
string test; // Error: identifier "string" is undefined
std::string test;
return 0;
}
Upvotes: 1
Reputation: 4673
Use a namespace alias.
namespace submod_ = topspace::other_project::module::submodule;
Then you can use submod_
wherever you would require the very long namespace.
This requires you to still use submod_
where you would have the long namespace qualifier. In that sense, it doesn't exactly answer your question. But I would argue that the explicitness of the qualification aids readability and helps prevent mistakes.
There are real examples of StackOverflow questions where a "using" declaration brought in "lurking" functions which the code author did not realize.
Upvotes: 1