Is there any semantic difference between the two in the title?
For example, I can write,
class Hi{
public:
static void Print(){
printf("hi\n");
}
};
but also,
namespace Hi{
inline void Print(){
printf("hi\n");
}
}
I'm of course assuming both of these definitions are in the header. Is it just a matter of style?
A main difference is that namespaces can be extended, while classes can be inherited. This difference was important for "enum wrappers" in C++03. Some people strongly favored wrapping enums in classes, and others strongly favored wrapping them in namespaces, while perhaps most didn't care and didn't wrap.
Namespaces support argument dependent lookup, while classes don't (except for calls of friend functions defined in class definitions, and then it's really namespace ADL kicking in).
Classes support access control (public, protected, private) while namespaces don't. With namespaces the technique corresponding to private access is a nested namespace called detail
or impl
or some such. But this is just convention, not something the compiler can check and enforce.
I guess that since the above is what occurred to me first, it's probably the most relevant.
Worth noting: libraries that uses classes as a kind of faux namespace mechanism do exist (in particular I ran into an XML parser library of that kind), but they are very rare, and I doubt that any new libraries do this except for possible the above mentioned enum wrapping, which however was made less important by the scoped enums of C++11.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다