【发布时间】:2021-04-26 11:32:04
【问题描述】:
我正在尝试使用一个宏,它利用预处理器__FUNCTION__ 切换到调用与宏调用者同名但在不同类中的函数。
(这是一个没有继承实现的简单模拟框架。)
#define FAKE(def) enabled(__FUNCTION__) ? def : _foo.__FUNCTION__()
用法是这样的:
#include <iostream>
struct Foo {
int bar() { return 42; }
};
#define FAKE(def) enabled() ? def : _foo.__FUNCTION__()
struct Fake {
Fake(Foo& foo) : _foo(foo) {}
Foo& _foo;
bool enabled(const char*) const { return true; } // for example
int bar() {
return FAKE(1337); // doesn't work
}
};
给出错误:
error: '__FUNCTION__' cannot be used as a function
这似乎是因为__FUNCTION__ 不是宏而是字符串文字。
有没有简单的解决方法?我不希望缓存一些字符串到函数指针或其他东西的映射。我知道 C++ 不支持反射,但我希望预处理器能以某种方式解决这个问题。
Live example
【问题讨论】:
-
另一个带有“不可能”cmets 的重复 Unquote __FUNCTION__ macro in C++。
-
#define FAKE(R, FUNC, DEFAULT) R FUNC() { return enabled(__FUNCTION__)?DEFAULT:_foo.FUNC(); }应该可以工作。可能需要FUNCEX(R, FUNC, MODIFIERS, DEFAULT)之类的。
标签: c++ c-preprocessor