如何动态设置类型

How do I dynamically set a type?

本文关键字:置类型 动态 何动态      更新时间:2023-10-16

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

现在,图是一个模板类Graph<K, V>,其中K是节点键的类型,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++中做到这一点?甚至可能吗?

如果你在编译时知道所有可能的type,那么使用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++是一种静态类型语言。您应该使用能够存储任何类型值的特定容器。看看 http://www.boost.org/doc/libs/1_60_0/doc/html/any.html。

来自提升站点的示例:

#include <list>
#include <boost/any.hpp>
using boost::any_cast;
typedef std::list<boost::any> many;
void append_int(many & values, int value)
{
    boost::any to_append = value;
    values.push_back(to_append);
}
void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}
void append_char_ptr(many & values, const char * value)
{
    values.push_back(value);
}
void append_any(many & values, const boost::any & value)
{
    values.push_back(value);
}
void append_nothing(many & values)
{
    values.push_back(boost::any());
}

所以在你的情况下,你可以有一个Graph<keyType, boost::any>图。您应该存储在图形中存储的类型的位置。但是在必须处理具体类型时,您将使用switch case语句

C++这是不可能的。模板是编译时构造。在其他语言中,相同的问题集通过不同的结构来解决,他们称之为"泛型",在运行时是可能的,但对于C++中的模板,它不是。