2016-03-07 77 views
0

我一直在尝试编写从文本输入文件读取并处理图形的代码。如何动态设置类型?

现在,图表是模板类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++?它甚至有可能吗?

+4

C++是一种静态类型语言,类型被设定在编译的时候,不能在运行时改变。所以不,你想做什么是不可能的,你必须想出另一种解决问题的方法。 –

+1

不,它不是。至少不是你想象的方式。模板实例化的类型是静态的,在任何文件打开之前的很长时间内都会被编译。 – StoryTeller

+0

您必须使用可以存储不同类型的对象。看一下boost :: any – Garf365

回答

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 
} 
0

在C++中,这是不可能的。模板是编译时间构造。在其他语言中,相同的问题集由一个不同的结构来解决,他们称之为“泛型”,在运行时可能会出现这种结构,但使用C++中的模板则不然。

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声明在一个时刻,当你要处理的具体类型