namespace first {
namespace second {
class Third {
static void foo() {
std::cout << "foo\n";
}
};
}
}
void bar() {
std::cout << "bar\n";
}
#define first::second::Third::foo bar//this doesn't work
那么,将一个嵌套函数映射到另一个函数的正确方法是什么呢?
更新:
更类似的情况是:
struct ReleaseVersion {
static void foo() {
std::cout << "release version\n";
}
};
struct DebugVersion {
static void foo() {
std::cout << "debug version\n";
}
};
#ifdef _DEBUG
#define ReleaseVersion::foo DebugVersion::foo
#else
#define DebugVersion::foo ReleaseVersion::foo
#endif
我想要做的就像malloc和_malloc_dbg一样,当#定义_CRTDBG_MAP_ALLOC时,在调试模式下,malloc将映射到_malloc_dbg,而在发布模式下,_malloc_dbg将映射到malloc
再次更新
更类似的情况是:
namespace first {
namespace second {
struct ReleaseVersion {
static void foo() {
std::cout << "release version\n";
}
};
struct DebugVersion {
static void foo(const char* file, long line) {
std::cout << "debug version\n";
}
};
}
}
#ifdef _DEBUG
#define ReleaseVersion::foo() DebugVersion::foo(__FILE__, __LINE__)
#else
#define DebugVersion::foo(file, line) ReleaseVersion::foo()
#endif
所以,这两个版本的函数可能有不同的参数,我不能只调用一个。我知道我能做到
#ifdef _DEBUG
#define Foo() first::second::DebugVersion::foo(__FILE__, __LINE__)
#else
#define Foo() first::second::ReleaseVersion::foo()
但在这种情况下,我必须始终使用Foo(),即使在最终发布模式中,它仍然是一个宏。我想知道是否有更灵活的方法来做到这一点。
一种解决方案
#ifdef _DEBUG
#define foo() foo(__FILE__, __LINE__)
#define ReleaseVersion DebugVersion
#else
#define foo(file, line) foo()
#define DebugVersion ReleaseVersion
#endif
int main() {
first::second::DebugVersion::foo(__FILE__, __LINE__);
first::second::ReleaseVersion::foo();
return 0;
}
当其他命名空间中有另一个foo()或RealeaseVersion/DebugVersion时,这可能是危险的,但如果你能确保没有,我认为它可以是一个可以接受的解决方案。
发布于 2013-02-20 19:09:44
你的#define
是错误的:
#define bar first::second::Third::foo
这意味着bar
将被first::second::Third::foo
取代,我相信这正是您想要的。
这是与typedef
相反的,在那里事情是相反的。
我不是很确定你想要什么,但这行得通:
namespace first {
namespace second {
class Third {
public: static void foo() {
std::cout << "foo\n";
}
};
}
}
#define bar first::second::Third::foo
int main()
{
bar();
}
发布于 2013-02-20 20:18:24
malloc
/free
的工作方式是通过宏替换:
#ifdef WANT_DEBUG_MALLOC
#define malloc(x) debug_malloc(x, __FILE__, __LINE__)
#define free(x) debug_free(x, __FILE__, __LINE__)
#endif
当预处理器看到struct foo *p = malloc(sizeof(struct foo) * 10);
时,它会用struct foo *p = debug_malloc(sizeof(struct foo) * 10, "myfile.c", 103);
替换它
然而,如上所述,在进行宏替换时,您不能真正使用名称空间。您必须单独替换命名空间,或者单独替换函数名。当然,也可以有两个宏,一个用来替换名称空间,另一个用来替换函数名。但它很快就会变得相当混乱,所以我想说,最好避免。
发布于 2013-02-20 20:31:33
我宁愿使用内联函数
#ifdef _DEBUG
static inline void DoFoo() { DebugVersion::foo(); }
#else
static inline void DoFoo() { ReleaseVersion::foo(); }
#endif
https://stackoverflow.com/questions/14978185
复制相似问题