namespace code example
Example 1: namespace
using namespace std;
namespace {
int x;
void display();
}
namespace{
void display(){
cout << "x is "<<x<<endl;
}
}
int main()
{
x = 25;
display();
return 0;
}
Example 2: namespace
// namespaces
using namespace std;
namespace foo
{
int value() { return 5; }
}
namespace bar
{
const double pi = 3.1416;
double value() { return 2*pi; }
}
int main () {
cout << foo::value() << '\n';
cout << bar::value() << '\n';
cout << bar::pi << '\n';
return 0;
}
Example 3: access the namespace members using namespace member function
//Header.h
namespace Test
{
namespace old_ns
{
std::string Func() { return std::string("Hello from old"); }
}
inline namespace new_ns
{
std::string Func() { return std::string("Hello from new"); }
}
}
int main()
{
using namespace Test;
using namespace std;
string s = Func();
std::cout << s << std::endl; // "Hello from new"
return 0;
}
Example 4: access the namespace members using namespace member function
namespace Parent
{
inline namespace new_ns
{
template <typename T>
struct C
{
T member;
};
}
template<>
class C<int> {};
}