如何动态设置类型?

时间:2016-03-07 12:18:14

标签: c++ class templates generics

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

现在,图表是模板类Graph<K, V>,其中K是节点的类型&#39; key和V是节点的类型&#39;值。

我想说我想从这种形式的文本文件中输入一个Graph:

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 ++中这样做?它甚至可能吗?

3 个答案:

答案 0 :(得分:5)

如果您在编译时知道所有可能的 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
}

答案 1 :(得分:1)

直接不可能。 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语句

答案 2 :(得分:0)

没有

在C ++中,这是不可能的。模板是编译时构造。在其他语言中,相同的问题集由他们称之为“#generics&#34;在运行时可能的地方,但在C ++中使用模板,它不是。