Sunday 11 August 2019

Use of namespace in C++?




#include "d3dApp.h"
#include

#include

namespace
{
// This is just used to forward Windows messages from a global window
// procedure to our member function window procedure because we cannot
// assign a member function to WNDCLASS::lpfnWndProc.
D3DApp* gd3dApp = 0;
}


LRESULT CALLBACK
MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// Forward hwnd on because we can get messages (e.g., WM_CREATE)
// before CreateWindow returns, and thus before mhMainWnd is valid.
return gd3dApp->MsgProc(hwnd, msg, wParam, lParam);
}


I am curious about this use of namespace in C++. I started reading the documentation on namespace and I saw a lot of examples calling a name for the namespace like "namespace first" but none without anything after the namespace declaration like this one.



Answer



This is an anonymous or unnamed namespace. Items in the namespace (just the gd3dApp in this example) are visible within a translation unit, but cannot be referred to externally because there is no name to qualify them with.



Note: this does not prevent external linkage. Take a look here: http://msdn.microsoft.com/en-us/library/yct4x9k5(v=vs.80).aspx.




Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.




This technique is slightly superior to static because it also works for typedefs (which can't be declared static).



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...