本文介绍了访问C ++函数从文本存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道如何完成以下操作:

I'm wondering if anyone knows how to accomplish the following:

假设我有一堆数据存储在SQL中,让我们说一个字段被称为funcName,函数名将包含类似于myFunction的数据我想知道是否有一种方式,我可以反过来提取函数名称,实际上调用该函数?

Let's say I have a bunch of data stored in SQL, lets say one of the fields could be called funcName, function name would contain data similar to "myFunction" What I'm wondering is, is there a way I can than in turn extract the function name and actually call that function?

有几种方法我可以想到来实现这一点,一个是将funcName更改为funcId和链接数组或类似,但我正在寻找一些更动态的东西,将允许我添加数据,而不必在每次添加对新函数的调用时更新实际的源代码,假设函数已经存在并且可以通过范围位置访问。

There's a few ways I can think of to accomplish this, one is changing funcName to funcId and linking up with an array or similar, but I'm looking for something a bit more dynamic that would allow me to add the data on fly without having to update the actual source code every time I add a call to a new function assuming of course that the function already exists and is accessible via scope location we call it from.

任何帮助将非常感激。

推荐答案

使用宏来定义自动注册自己的新函数。 / p>

Use a macro to define new functions that register themselves automatically.

// callable_function.h
class CallableFunction {
 public:
  virtual void operator()() = 0;
};

class CallableFunctionRegistry {
 public:
  static CallableFunction *Register(const string &func_name,
                                    CallableFunction *func_impl) {
    Instance()->registered_functions_.insert(make_pair(func_name, func_impl));
  }

  static void Run(const string &func_name) {
    (*Instance()->registered_functions_[func_name])();
  }

 private:
  static CallableFunctionRegistry *Instance() {
    static CallableFunctionRegistry *instance = new CallablefunctionRegistry;
    return instance;
  }

  CallableFunctionRegistry() {}
  map<string, CallableFunction*> registered_functions_;
};

#define REGISTER_CALLABLE_FUNCTION(FuncName) \
  class FuncName : public CallableFunction { \
   public: \
    virtual void operator()(); \
  }; \
  CallableFunction *impl_ ##FuncName = \
    CallableFunctionRegistry::Register(#FuncName, new FuncName); \
  void FuncName::operator()()
//other_file.cc
REGISTER_CALLABLE_FUNCTION(DoStuff) {
  // do stuff here.
}

而且:

//yet_another_file.cc
CallableFunctionRegistry::Run("DoStuff");

你可以使用函数ptrs而不是CallableFunction对象,但是我的语法是模糊的。无论如何,添加错误检查重复注册和查找未找到。

You could do it with function ptrs instead of CallableFunction object, but my syntax on that is hazy. Either way, add error checking for duplicate registrations and lookup not found.

这篇关于访问C ++函数从文本存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:52