C++ 方法按名称解析

标签 c++ templates reflection template-meta-programming higher-order-functions

我想知道 C++ 中是否有一种方法可以编写一个函数,该函数将仅根据方法名称解析对象方法(具体示例如下)。运行时或编译时解析(例如模板)都是可以接受的。我已经阅读了一些有关模板元编程的内容,但我希望在深入研究之前我可以获得一些关于这是否适合我的问题的方向的信息。

本质上,我正在尝试编写一个函数来调用传入对象的非静态方法,例如这个伪代码:

exampleFunction(Object myObject, ObjectMethod myObjectMethod) {
    // do some stuff here

    myObject.myObjectMethod(arguments);

    // do some more stuff here
}

在这种情况下,我无法将方法硬编码到 exampleFunction 中,并且只能让我调用它的每个对象都具有该方法名称。我必须能够灵活地使用各种方法调用 exampleFunction,并正确解析每个方法。此外,我必须能够解析方法,并且这些方法必须是非静态的。就我而言,我必须能够修改方法调用上的内部私有(private)对象成员。无需深入了解细节,这些约束是我正在开发的系统的产物,我无法更改。

正如我之前所说,编译时和运行时解决方案都是可以接受的。因此,像这样的模板在我的情况下也能完美地工作:

template <ObjectMethodName methodName>
exampleFunction(Object myObject) {
    // do some stuff here

    myObject.methodName(arguments);

    // do some more stuff here
}

任何关于这是否可能的想法,以及有关可能实现的信息,我们将不胜感激。

最佳答案

您可以使exampleFunction成为一个函数模板,它的第一个参数是对象类型,第二个参数可以是对成员函数指针的引用,第三个参数是函数参数包,表示调用成员函数时要传递的参数。

#include <iostream>

class Actions {
  public:
    Actions(){}
    void doSmthg(){
        std::cout<<"do something called"<<std::endl;
    }
    void multipleArgs(int, int)
    {
        std::cout<<"multiple int args called"<<std::endl;
    }
};
class Entity
{
    public:
    void func(double)
    {
        std::cout<<"func called"<<std::endl;
    }
};
template<typename T, typename Callable, typename... Args>
void exampleFunction(T obj, const Callable& callable, const Args&... args){
    std::cout<<"exampleFunction called"<<std::endl;
    //call the function on the passed object
    (obj.*callable)(args...);
}


int main()
{
    Actions action;
    
    exampleFunction(action, &Actions::doSmthg); //calls doSmthg member function with 0 arguments 
    exampleFunction(action, &Actions::multipleArgs, 5,7);//calls multipleArgs member function with 2 int arguments
    
    Entity e;
    exampleFunction(e, &Entity::func,4.4); //calls func member function 
}

Demo

上述程序的输出为:

exampleFunction called
do something called
exampleFunction called
multiple int args called
exampleFunction called
func called

关于C++ 方法按名称解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71860616/

相关文章:

c++ - 在 C 中创建 cout 函数?

C++ 将新类对象添加到数组中的新位置

c++ - 在 C++ 中使用模板测试字符串或其他数据类型数组

c# - 评论存储在哪里以及如何提取它们?

reflection - 如何通过反射访问字段的值(Scala 2.8)

C++创建一个函数的 friend ?

c++ - 在线程中等待一段时间,或者直到条件发生

c++ - 模板堆栈没有推送?

templates - 推断模板中的 lambda 返回类型

c# - 通用 Windows 平台 (UWP) 中的反射缺少属性