我试图做一个奇特的宏来获得一些调试信息:你现在的范围的名字!这可以通过例如一个断言。我试图使它递归:如何递归访问父范围?
// Global namespace
struct ScopeDef{ static const char* GetName() {return "";} };
typedef ScopeDef ScopeDefParent;
// Macro to place into your namespace/scope
#define NG_SCOPEDEF(scopename) \
struct ScopeDef { \
static const char* GetName() {return scopename;} \
typedef ScopeDefParent Parent; \
}; \
typedef ScopeDef ScopeDefParent;
,并用它喜欢:
// Recursive template for testing
template< class T > void PrintImpl() {
PrintImpl<T::Parent>();
printf("::%s", T::GetName());
}
template<> void PrintImpl<::ScopeDef>() {}
template< class T > void PrintS() { PrintImpl<T>(); printf("\n");}
// Lets try it:
namespace First {
NG_SCOPEDEF("First");
namespace Second {
NG_SCOPEDEF("Second");
static void AFun() {
// This prints "::First::Second"
PrintS<ScopeDef>();
}
}
struct Third {
NG_SCOPEDEF("Third");
static void BFun() {
// This is endless recursion
PrintS<ScopeDef>();
}
};
}
它不会在类范围工作,因为定义的顺序并不重要。
这不是一个很好的解决方案。那么有没有办法以某种方式访问父范围?在常规代码中,我只会限定(“:: First :: ScopeDef”),但这对于宏来说没有任何意义。
你有一个很好的理由不使用__FILE__和__LINE__其粗略地讲给出相同的信息? – stijn 2013-02-21 16:42:08
他们是有帮助的,是的,但不一样。我脑海中的大部分东西都会像上面的模板PrintS <>一样使用结构。 – Borph 2013-02-21 16:46:08