在C++中创建和调用动态类方法的最简单方法是什么?

3
我希望能够填充一个地图,其中包含类名和方法、唯一标识符以及指向该方法的指针。
typedef std::map<std::string, std::string, std::string, int> actions_type;
typedef actions_type::iterator actions_iterator;

actions_type actions;
actions.insert(make_pair(class_name, attribute_name, identifier, method_pointer));

//after which I want call the appropriate method in the loop

while (the_app_is_running)
{
    std::string requested_class = get_requested_class();
    std::string requested_method = get_requested_method();

    //determine class
    for(actions_iterator ita = actions.begin(); ita != actions.end(); ++ita)
    {
        if (ita->first == requested_class && ita->second == requested_method)
        {
            //class and method match
            //create a new class instance
            //call method
        }
    }
}

如果该方法是静态的,那么一个简单的指针就足够了,问题很简单,但我想动态创建对象,所以我需要存储类的指针和方法的偏移量,而我不知道这是否有效(如果偏移量总是相同等)。
问题在于C++缺乏反射,一个具有反射功能的解释性语言中的等效代码应该如下所示(PHP示例):
$actions = array
(
     "first_identifier" => array("Class1","method1"),
     "second_identifier" => array("Class2","method2"),
     "third_identifier" => array("Class3","method3")
);

while ($the_app_is_running)
{
     $id = get_identifier();

     foreach($actions as $identifier => $action)
     {
         if ($id == $identifier)
         {
             $className = $action[0];
             $methodName = $action[1];

             $object = new $className() ;

             $method = new ReflectionMethod($className , $methodName);
             $method -> invoke($object);    
         }
     }
 }

PS:是的,我正在尝试用C++制作一个(Web)MVC前端控制器。 我知道,我知道,为什么不使用PHP、Ruby、Python(在这里插入你最喜欢的Web语言)等呢?我只是想用C++。


1
不要强制将C++变成动态语言。使用基类和虚函数,并考虑您想要调用的接口。 - gbjbaanb
是的,如果不经过一些努力工作,你所寻找的东西是很难实现的。 - Johannes Schaub - litb
8个回答

7

也许您正在寻找成员函数指针

基本用法:

class MyClass
{
    public:
        void function();
};

void (MyClass:*function_ptr)() = MyClass::function;

MyClass instance;

instance.*function_ptr;

正如C++ FAQ Lite中所述,当使用成员函数指针时,宏和typedef会极大地增加可读性(因为它们的语法在代码中并不常见)。

@orip,当有人试图在虚函数更为适合的情况下使用它们时,我感到非常心痛。 - strager
不要担心你不知道它将被称为什么。在我的情况下,它将被保存在数据库中,并稍后调用,因此我将映射一些内容并在运行时使用它,如果这样做可以解决我的问题,那就加1。 - Jonathan

5

我在前几个小时写了这些东西,并将其添加到我的有用工具集中。最困难的是处理工厂函数,如果你想要创建的类型没有任何关联。我使用了 boost::variant 来解决这个问题。你必须给它一组你想要使用的类型。然后它会跟踪变体中当前“活动”的类型。(boost::variant 是所谓的带标签联合)。第二个问题是如何存储函数指针。问题是无法将指向 A 的成员的指针存储到指向 B 的成员的指针中。这些类型是不兼容的。为了解决这个问题,我将函数指针存储在一个重载了其 operator() 并接受 boost::variant 的对象中。

return_type operator()(variant<possible types...>)

当然,你所有类型的函数都必须具有相同的返回类型。否则整个程序将毫无意义。现在看一下代码:
#include <boost/variant.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/function_arity.hpp>
#include <boost/preprocessor/repetition.hpp>
#include <map>
#include <string>
#include <iostream>

// three totally unrelated classes
// 
struct foo {
    std::string one() {
        return "I ";
    }
};

struct bar {
    std::string two() {
        return "am ";
    }
};

struct baz {
    std::string three() const {
        return "happy!";
    }
};

// The following are the parameters you have to set
//

// return type
typedef std::string return_type;
// variant storing an object. It contains the list of possible types you
// can store.
typedef boost::variant< foo, bar, baz > variant_type;
// type used to call a function on the object currently active in
// the given variant
typedef boost::function<return_type (variant_type&)> variant_call_type;

// returned variant will know what type is stored. C++ got no reflection, 
// so we have to have a function that returns the correct type based on
// compile time knowledge (here it's the template parameter)
template<typename Class>
variant_type factory() {
    return Class();
}

namespace detail {
namespace fn = boost::function_types;
namespace mpl = boost::mpl;

// transforms T to a boost::bind
template<typename T>
struct build_caller {
    // type of this pointer, pointer removed, possibly cv qualified. 
    typedef typename mpl::at_c<
        fn::parameter_types< T, mpl::identity<mpl::_> >,
        0>::type actual_type;

    // type of boost::get we use
    typedef actual_type& (*get_type)(variant_type&);

// prints _2 if n is 0
#define PLACEHOLDER_print(z, n, unused) BOOST_PP_CAT(_, BOOST_PP_ADD(n, 2))
#define GET_print(z, n, unused)                                         \
    template<typename U>                                                \
    static variant_call_type get(                                       \
        typename boost::enable_if_c<fn::function_arity<U>::value ==     \
            BOOST_PP_INC(n), U>::type t                                 \
        ) {                                                             \
        /* (boost::get<actual_type>(some_variant).*t)(n1,...,nN) */     \
        return boost::bind(                                             \
            t, boost::bind(                                             \
                (get_type)&boost::get<actual_type>,                     \
                _1) BOOST_PP_ENUM_TRAILING(n, PLACEHOLDER_print, ~)     \
            );                                                          \
    }

// generate functions for up to 8 parameters
BOOST_PP_REPEAT(9, GET_print, ~)

#undef GET_print
#undef PLACEHOLDER_print

};

}

// incoming type T is a member function type. we return a boost::bind object that
// will call boost::get on the variant passed and calls the member function
template<typename T>
variant_call_type make_caller(T t) {
    return detail::build_caller<T>::template get<T>(t);
}

// actions stuff. maps an id to a class and method.
typedef std::map<std::string, 
                 std::pair< std::string, std::string >
                 > actions_type;

// this map maps (class, method) => (factory, function pointer)
typedef variant_type (*factory_function)();
typedef std::map< std::pair<std::string,      std::string>, 
                  std::pair<factory_function, variant_call_type> 
                  > class_method_map_type;

// this will be our test function. it's supplied with the actions map, 
// and the factory map
std::string test(std::string const& id,
                 actions_type& actions, class_method_map_type& factory) {
    // pair containing the class and method name to call
    std::pair<std::string, std::string> const& class_method =
        actions[id];

    // real code should take the maps by const parameter and use
    // the find function of std::map to lookup the values, and store
    // results of factory lookups. we try to be as short as possible. 
    variant_type v(factory[class_method].first());

    // execute the function associated, giving it the object created
    return factory[class_method].second(v);
}

int main() {
    // possible actions
    actions_type actions;
    actions["first"] = std::make_pair("foo", "one");
    actions["second"] = std::make_pair("bar", "two");
    actions["third"] = std::make_pair("baz", "three");

    // connect the strings to the actual entities. This is the actual
    // heart of everything.
    class_method_map_type factory_map;
    factory_map[actions["first"]] = 
        std::make_pair(&factory<foo>, make_caller(&foo::one));
    factory_map[actions["second"]] = 
        std::make_pair(&factory<bar>, make_caller(&bar::two));
    factory_map[actions["third"]] = 
        std::make_pair(&factory<baz>, make_caller(&baz::three));

    // outputs "I am happy!"
    std::cout << test("first", actions, factory_map)
              << test("second", actions, factory_map)
              << test("third", actions, factory_map) << std::endl;
}

这段代码使用了boost preprocessor、function types和bind library等技术。可能看起来比较复杂,但只要掌握了其中的关键,就不难理解了。如果你想改变参数数量,只需要调整variant_call_type即可。

typedef boost::function<return_type (variant_type&, int)> variant_call_type;

现在您可以调用需要一个整数参数的成员函数。以下是调用示例:

return factory[class_method].second(v, 42);

玩得开心!


如果你现在觉得上面的内容太复杂了,我必须同意你的看法。这是因为C++并不是为这样的动态使用而设计的。如果您可以将方法分组并实现在要创建的每个对象中,则可以使用纯虚函数。或者,您可以在默认实现中抛出一些异常(例如std::runtime_error),以便派生类不需要实现所有内容:

struct my_object {
    typedef std::string return_type;

    virtual ~my_object() { }
    virtual std::string one() { not_implemented(); }
    virtual std::string two() { not_implemented(); }
private:
   void not_implemented() { throw std::runtime_error("not implemented"); }
};

如果要创建对象,通常的工厂就可以。

struct object_factory {
    boost::shared_ptr<my_object> create_instance(std::string const& name) {
        // ...
    }
};

地图可以由一个将ID映射到类和函数名称的地图和一个将其映射到boost::function的地图组成:
typedef boost::function<my_object::return_type(my_object&)> function_type;
typedef std::map< std::pair<std::string, std::string>, function_type> 
                  class_method_map_type;
class_method_map[actions["first"]] = &my_object::one;
class_method_map[actions["second"]] = &my_object::two;

调用该函数的方式如下所示:
boost::shared_ptr<my_object> p(get_factory().
    create_instance(actions["first"].first));
std::cout << class_method_map[actions["first"]](*p);

当然,采用这种方法,您会失去灵活性和(可能,未进行过剖析)效率,但可以极大地简化设计。

3
我认为在这里找出的最重要的事情是,你所有的方法是否具有相同的签名?如果是,这是boost bind(如果你喜欢的话)的一个微不足道的用途,函数对象是一种选择(静态、鸭子类型的函数对象),或者只是普通的虚继承也是一种选择。虚继承目前不太流行,但很容易理解,我认为它并没有比使用boost bind更复杂(在我看来,对于小型非系统性函数对象来说,boost bind是最好的选择)。
以下是一个示例实现。
#include<iostream>
#include<map>
#include<string>

using std::map;
using std::string;
using std::cout;
using std::pair;

class MVCHandler
{
public:
    virtual void operator()(const string& somekindofrequestinfo) = 0;
};

class MyMVCHandler : public MVCHandler
{
public:
    virtual void operator()(const string& somekindofrequestinfo)
    {
        cout<<somekindofrequestinfo;
    }
};

void main()
{
    MyMVCHandler myhandler;
    map<string, MVCHandler*> handlerMap;
    handlerMap.insert(pair<string, MVCHandler*>("mysuperhandler", &myhandler));
    (*handlerMap["mysuperhandler"])("somekindofrequestdata");
}

2

和许多C++问题一样,这看起来是Boost的另一个应用。您基本上想要存储boost::bind(&Class::member, &Object)的结果。[编辑]使用boost::function很容易存储这样的结果。


使用boost::function存储你的boost::bind结果。 - Matt Cruikshank

1

你可以尝试使用工厂或抽象工厂设计模式来处理这个类,并使用函数指针来处理该函数。

当我搜索类似问题的解决方案时,我找到了以下两个实现页面:

工厂模式

抽象工厂模式


就我所知,这并没有解释通过名称调用成员函数的问题。 - strager
+1 建议使用工厂动态创建类实例。 - strager

1

如果您不想使用成员函数指针,您可以使用带有类实例参数的静态函数。例如:

class MyClass
{
    public:
        void function();

        static void call_function(MyClass *instance);  // Or you can use a reference here.
};

MyClass instance;
MyClass::call_function(&instance);

这需要程序员更多的工作,并会导致可维护性问题(因为如果您更新其中一个的签名,您也必须更新另一个的签名)。

您还可以使用一个单一的静态函数来调用所有成员函数:

class MyClass
{
    public:
        enum Method
        {
            fp_function,
        };

        void function();

        static void invoke_method(MyClass *instance, Method method);  // Or you can use a reference here.
};

void MyClass::invoke_method(MyClass *instance, Method method)
{
    switch(method)
    {
        default:
            // Error or something here.
            return;

        case fp_function:
            instance->function();
            break;

        // Or, if you have a lot of methods:

#define METHOD_CASE(x) case fp_##x: instance->x(); break;

        METHOD_CASE(function);

#undef METHOD_CASE
    }

    // Free logging!  =D
}

MyClass instance;
MyClass::invoke_method(instance, MyClass::fp_function);

0

您还可以使用函数的动态加载:

在Windows中使用GetProcAddress,在Unix中使用dlsym。


这里存在一个问题,它被称为名称修饰。很可能,C++编译器会对命名空间和重载冲突解决进行函数名修饰。也许有一些非标准的函数可以检索到被修饰后的名称。 - strager

0

采用观察者设计模式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接