C++: How to force libc declarations into std::?

社会主义新天地 提交于 2019-12-22 06:53:54

问题


So, I find myself in the need of libc in my C++ program. However, I do not like the idea of sprinkling it all over the global namespace. Ideally, I'd like to force the entirety of libc into the std:: namespace so I'd have to do std::memcpy rather than memcpy.

Is this possible? And how? I'm willing to use compiler-specific macros if needed (I target only MS VC++ 10.0 and GCC 4.6).

Edit: I do literally mean 'force the declarations into std' - so that they are uncallable without the std:: prefix. Also, I am including cstdio, not stdio.h.

Thanks!


回答1:


You cannot do this, unless it's already done.

The namespace std is reserved to the Standard Library, it is forbidden to add new members to this namespace. Therefore, if the C-headers are not already embedded within std, then you have no choice but to accept it.

On the other hand, you can perfectly create a new namespace, cstd, and bring the symbols from the global namespace in it with using directives... but it won't make them disappear from the global namespace.




回答2:


I do literally mean 'force the declarations into std' - so that they are uncallable without the std:: prefix.

You can't do this if your implementation exposes the names in the global namespace. You can use the <cXXX> headers and then use std:: yourself.

This is, perhaps, unfortunate, but it is a consequence of C compatibility, since C does not understand namespaces. C++ has traditionally maintained many kludges and sacrifices for C compatibility.




回答3:


Make wrapper includes

//stdlib.hpp
namespace std
{
#include <stdlib.h> //edit: changed from cstdlib to stdlib.h
}

If the linker hates this try just declaring the functions you want:

namespace std{ extern "C" {

int memcpy( void *out, const void *in);
} }



回答4:


The reason some (most?) C++ compilers have the C functions in the global namespace, is simply that they have to use the existing operating system functions. For example, the file functions might not be a separate C library, but the file handling of the OS.



来源:https://stackoverflow.com/questions/4909420/c-how-to-force-libc-declarations-into-std

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!