gpt4 book ai didi

c++ - 在 C++ 中根据运行时字符串选择模板

转载 作者:可可西里 更新时间:2023-11-01 16:35:24 27 4
gpt4 key购买 nike

我有一个可以容纳不同类型的属性 vector :

class base_attribute_vector; // no template args

template<typename T>
class raw_attribute_vector : public base_attribute_vector;

raw_attribute_vector<int> foo;
raw_attribute_vector<std::string> foo;

基于类型的运行时输入,我想创建适当的数据结构。伪代码:

std::string type("int");
raw_attribute_vector<type> foo;

显然,这失败了。一个简单但丑陋且无法维护的解决方法是运行时切换/链接,如果:

base_attribute_vector *foo;
if(type == "int") foo = new raw_attribute_vector<int>;
else if(type == "string") ...

我阅读了关于仿函数的运行时多态性,但发现它对于一个概念上很容易的任务来说相当复杂。

使这项工作最好和最干净的方法是什么?我尝试了 boost::hana,发现虽然我可以创建从字符串到类型的映射,但查找只能在编译时完成:

auto types = 
hana::make_map(
hana::make_pair(BOOST_HANA_STRING("int"), hana::type_c<int>),
hana::make_pair(BOOST_HANA_STRING("string"), hana::type_c<std::string>)
);

所有可能的类型在编译时都是已知的。任何建议都非常感谢。在一个完美的解决方案中,我会在一个地方创建 name->type 映射。之后,我会这样使用它

std::vector<base_attribute_vector*> foo;

foo.push_back(magic::make_templated<raw_attribute_vector, "int">);
foo.push_back(magic::make_templated<raw_attribute_vector, "std::string">);

foo[0]->insert(123);
foo[1]->insert("bla");

foo[0]->print();
foo[1]->print();

这种魔法不需要在编译时发生。我的目标是拥有尽可能可读的代码。

最佳答案

我会使用 std::map,它以字符串作为键,以 std::function 作为值。我会将字符串与返回您的类型的函数相关联。这是一个例子:

using functionType = std::function<std::unique_ptr<base_attribute_vector>()>;
std::map<std::string, functionType> theMap;

theMap.emplace("int", []{ return new raw_attribute_vector<int>; });
theMap.emplace("float", []{ return new raw_attribute_vector<float>; });

// Using the map
auto base_vec = theMap["int"](); // base_vec is an instance of raw_attribute_vector<int>

当然,如果你只知道运行时的字符串值,这个解决方案是有效的。

关于c++ - 在 C++ 中根据运行时字符串选择模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644146/

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