views:

316

answers:

2
namespace A
{
   #include <iostream>
};

int main(){
 A::std::cout << "\nSample";
 return 0;
}
+5  A: 

Short answer: No.

Long answer: Well, not really. You can fake it, though. You can declare it outside and use using statements inside the namespace, like this:

#include <iostream>

namespace A
{
   using std::cout;
};

int main(){
 A::cout << "\nSample";
 system("PAUSE");
 return 0;
}

You cannot localize a library, because even if it had access in A, it would not have access in the standard namespace.

Also, "The other problem is that the qualified names inside the namespace would be A::std::cout, but the library would not contain names qualified with the outer namespace." thanks Jonathon Leffler.

If the problem is that you don't want to let other people know what all your code can do, you could have your own cpp file to include iostream in, and have the namespace defined there. Then you just include that in main (or whatever) and let the programmer know what he can and cannot do.

Hooked
The other problem is that the qualified names inside the namespace would be A::std::cout, but the library would not contain names qualified with the outer namespace.
Jonathan Leffler
Very good point, thanks. Added. +1
Hooked
adatapost
+3  A: 

You could write:

#include <vector> // for additional sample
#include <iostream>
namespace A
{
  namespace std = std; // that's ok according to Standard C++ 7.3.2/3
};

// the following code works
int main(){
 A::std::cout << "\nSample"; // works fine !!!
 A::std::vector<int> ints;
 sort( ints.begin(), ints.end() );  // works also because of Koenig lookup

 std::cout << "\nSample";  // but this one works also
 return 0;
}

Thit approach is called namespace aliasing. Real purpose for that feature showed in the following sample:

namespace Company_with_very_long_name { /* ... */ }
namespace CWVLN = Company_with_very_long_name;

// another sample from real life
namespace fs = boost::filesystem;
void f()
{
  fs::create_directory( "foobar" );   // use alias for long namespace name
}
Kirill V. Lyadvinsky
Great explanation. Thanks Jla3ep.
adatapost