如何在运行时使用C ++在工厂类中动态注册类 [英] How to dynamically register class in a factory class at runtime period with c++
问题描述
现在,我实现了一个工厂类以使用标识字符串动态创建类,请参见以下代码:
Now, I implemented a factory class to dynamically create class with a idenification string, please see the following code:
void IOFactory::registerIO()
{
Register("NDAM9020", []() -> IOBase * {
return new NDAM9020();
});
Register("BK5120", []() -> IOBase * {
return new BK5120();
});
}
std::unique_ptr<IOBase> IOFactory::createIO(std::string ioDeviceName)
{
std::unique_ptr<IOBase> io = createObject(ioDeviceName);
return io;
}
因此我们可以使用注册名称创建IO类:
So we can create the IO class with the registered name:
IOFactory ioFactory;
auto io = ioFactory.createIO("BK5120");
此方法的问题是,如果我们添加另一个IO组件,则应该在registerIO中添加另一个注册码再次编译整个项目。因此,我想知道是否可以在运行时从配置文件(见下文)动态注册类。
The problem with this method is if we add another IO component, we should add another register code in registerIO function and compile the whole project again. So I was wondering if I could dynamically register class from a configure file(see below) at runtime.
io_factory.conf
------------------
NDAM9020:NDAM9020
BK5120:BK5120
------------------
第一个是标识名,第二个是类名。
The first is identification name and the second is class name.
我尝试使用宏,但是宏中的参数不能为字符串。所以我想知道是否还有其他方法。
I have tried with Macros, but the parameter in Macros cann't be string. So I was wondering if there is some other ways. Thanks for advance.
更新:
我没想到会有如此多的评论和答案,谢谢大家,很抱歉延迟回复。
I didn't expect so many comments and answers, Thank you all and sorry for replying late.
我们当前的操作系统是Ubuntu16.04,我们使用内置的编译器是gcc / g ++ 5.4.0,我们使用CMake来管理构建。
Our current OS is Ubuntu16.04 and we use the builtin compiler that is gcc/g++5.4.0, and we use CMake to manage the build.
我应该指出,这不是必须的在运行时注册类,如果在编译期间有办法这样做也可以。我想要的只是在我要注册另一个类时避免重新编译。
And I should mention that it is not a must that I should register class at runtime period, it is also OK if there is a way to do this in compile period. What I want is just avoiding the recompiling when I want to register another class.
推荐答案
所以我我想知道我是否可以在运行时从配置文件(见下文)动态注册类。
So I was wondering if I could dynamically register class from a configure file(see below) at runtime.
否。从C ++ 20开始,C ++没有允许的反射功能。但是您可以在编译时通过从配置文件生成一个简单的C ++实现文件来做到这一点。
No. As of C++20, C++ has no reflection features allowing it. But you could do it at compile time by generating a simple C++ implementation file from your configuration file.
这篇关于如何在运行时使用C ++在工厂类中动态注册类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!