![](/img/trans.png)
[英]What is the best\simplest\fastest way to create set of 1 element? (C++)
[英]What is the simplest way to create and call dynamically a class method in C++?
我想用類名和方法填充一個映射,一個唯一的標識符和指向該方法的指針。
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(在這里插入你最喜歡的網絡語言)等等,我只想要C ++。
也許你正在尋找成員函數指針 。
基本用法:
class MyClass
{
public:
void function();
};
void (MyClass:*function_ptr)() = MyClass::function;
MyClass instance;
instance.*function_ptr;
正如C ++ FAQ Lite中所述,使用成員函數指針時,宏和typedef
會大大提高可讀性(因為它們的語法在代碼中並不常見)。
我在最后幾個小時寫了這些東西,並將它添加到我的有用的東西集合中。 如果您要創建的類型不以任何方式相關,最困難的是應對工廠功能。 我為此使用了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預處理器,函數類型和綁定庫的非常有趣的技術。 可能循環復雜,但如果你得到該代碼中的鍵,那就不再需要掌握了。 如果要更改參數計數,只需調整variant_call_type即可:
typedef boost::function<return_type (variant_type&, int)> variant_call_type;
現在,您可以調用帶有int的成員函數。 以下是呼叫方面的外觀:
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);
當然,通過這種方法,您可以放松靈活性(可能沒有分析)效率,但是您可以大大簡化設計。
像許多C ++問題一樣,這看起來像Boost的另一個應用程序。 你基本上想要存儲boost :: bind(&Class :: member,&Object)的結果。 [edit]使用boost :: function存儲這樣的結果很容易。
我認為這里最重要的一點是,你的所有方法都有相同的簽名嗎? 如果他們這樣做,這是一個微不足道的使用boost綁定(如果你是這樣),functor是一個選項(靜態,duck類型),或只是普通的ole虛擬繼承是一個選項。 繼承目前還不流行,但它很容易理解,我不認為它使事情變得復雜,然后使用boost bind(imho最適合小型非系統函子)。
這是一個示例實現
#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");
}
如果您不想使用成員函數指針 ,則可以使用帶有類實例參數的靜態。 例如:
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);
您還可以使用動態加載功能:
在Windows中使用GetProcAddress,在Unix中使用dlsym。
去主題觀察者設計模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.