jeudi 27 août 2015

C++ preprocessor token pasting for namespace qualification

I am having trouble with the preprocessor token pasting operator in gcc 4.7.1 (std=c++11). Namely, consider the following code:

// Create a name for a global map (this works)
#define GLOBAL_MAP(name) g_map_ ## name // This works fine

// Now, namespace qualify this map (this fails to compile when used)
#define NS_QUAL_GLOBAL_MAP(name) SomeNamespace:: ## GLOBAL_MAP(name)

Usage scenarios - first the map definitions:

std::map<std::string,std::string> GLOBAL_MAP(my_map);

namespace SomeNamespace
{

std::map<std::string,std::string> GLOBAL_MAP(my_map);

}

Now the usage:

void foo()
{
    bar(GLOBAL_MAP(my_map)); // This compiles fine
    baz(NS_QUAL_GLOBAL_MAP(my_map)); // This fails to compile with:
                                     // error: pasting "::" and "NAME_MAP" does not give a
                                     // valid preprocessing token
}

What I believe might be happening is that it is interpreting GLOBAL_MAP after ## as a token for pasting rather than a macro to be further expanded. How do I get around this?

Aucun commentaire:

Enregistrer un commentaire