【问题标题】:Use __FUNCTION__ to call the function with the same name in another class [duplicate]使用__FUNCTION__调用另一个类中的同名函数[重复]
【发布时间】: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


【解决方案1】:

有简单的解决方法吗?

没有。

我不希望缓存一些字符串到函数指针或其他东西的映射

如果您想要运行时调度,那么这就是要走的路。

我知道 C++ 不支持反射,但我希望预处理器能以某种方式解决这个问题。

而且因为 C++ 不支持反射,所以没有语言特性会“解决这个问题”。该语言本身不支持通过字符串表示来查找函数。预处理器是一个(简单的)字符串替换工具。 __FUNCTION__ 不是字符串文字 - __FUNCTION__ 的工作方式就像在函数中定义 static const char * 变量一样。不要使用__FUNCTION__,它是一个扩展,使用__func__。在 C++20 中,请参阅 source_location

但是没有必要使用反射。在 C++ 中,使用 SFINAE。在 C++17 中,有 if constexpr。在 C++20 中,有一些概念。例如见this answer to Templated check for the existence of a class member function?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多