gpt4 book ai didi

c++ - 如何实例化其构造函数需要来自包含类名的字符串的参数的对象?

转载 作者:行者123 更新时间:2023-11-28 08:16:12 27 4
gpt4 key购买 nike

Is there a way to instantiate objects from a string holding their class name?

我遇到了一个与上述问题基本相同的问题。但是我需要用一些参数实例化一个类。不同的类构造函数名称可能需要不同数量的变量,并且每个变量的类型也可能不同。并且由于该类包含常量变量,因此您无法使用 new T() 对其进行新建,然后将参数设置为正确的值。 “类名”-“构造函数”映射似乎不适合我的需要。

还有其他选择吗?

最佳答案

我要在开头说,无论您想要完成什么,C++ 都不是正确的语言。您越是尝试通过外部数据来控制您的程序,您就越接近完全使用脚本。如果这是您的目标,还有许多更强大的选项。

也就是说,当然,这是可能的,尽管并不那么容易。立即想到两种方法。第一个是要求所有适用的类型都有一个接受 std::string 的构造函数。这个构造函数将负责它自己的解析。

template<typename T> Base * createInstance(const std::string& s) { return new T(s); }
typedef std::map<std::string, Base*(*)(const std::string&)> map_type;
//...and similar changes as needed

如果你不想改变你的类型定义,或者这是 Not Acceptable [也许你的类型已经有这样的构造函数?],摆脱模板化的 createInstance 方法,并提供单独的您感兴趣的每种类型的版本。此函数进行解析,并调用适当的构造函数。

map["derivedA"] = createDerivedA;
map["derivedB"] = createDerivedB;

第三种选择可能可以使用可变参数模板[或 boost-esque 可变参数样模板],这将使您回到最初的简单性。

template<typename T, typename... Args>
Base* create(std::string) {
//somehow pass the string to a generic function that packs the arguments into a tuple
//then somehow unpack that tuple and pass the bits to the constructor
}

map["derivedA"] = create<derivedA, int, double, std::string>;

但是,我不知道如何实现它,甚至不知道它是否可能。

关于c++ - 如何实例化其构造函数需要来自包含类名的字符串的参数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com