Can I include iostream header file into custom nam

2019-03-22 00:06发布

namespace A
{
   #include <iostream>
};

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

2条回答
萌系小妹纸
2楼-- · 2019-03-22 00:52

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-03-22 01:03

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
}
查看更多
登录 后发表回答