gpt4 book ai didi

c++ - 如何动态设置类型?

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:11 24 4
gpt4 key购买 nike

我一直在尝试编写从文本输入文件读取和初始化图形的代码。

现在,图是一个模板类Graph<K, V> , 其中K是节点 key 的类型,V是节点值的类型。

假设我想从这种形式的文本文件中获取图形输入:

char;int    // the types
a;b;c // the keys
a;b,32;c,5 // edges starting from a
b;c,2 // edges starting from b

如何将类型存储在变量中以初始化图形?

我想做这样的事情:

getline(file, value, ';');
string keyTypeString = value;
getline(file, value);
string valueTypeString = value;

type keyType = ...
type valueType = ...

Graph<keyType, valueType> graph = ...

我如何在 C++ 中做到这一点?有可能吗?

最佳答案

如果您在编译时知道所有可能 类型,那么使用Boost.Variant .文档中有很多示例,但本质上您将拥有类似的内容:

using type = boost::variant<char, int>;

std::string input;
std::getline(file, input);

type value;

try {
value = boost::lexical_cast<int>(input);
} catch(const boost::bad_lexical_cast&) {
value = input.front(); // char
}

关于c++ - 如何动态设置类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35843574/

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