将向量的元素转换为T C ++类型

时间:2015-03-13 01:34:54

标签: c++ templates vector type-conversion

我有一个名为load的模板化函数用于加载文本文件的类,然后在load函数内部,我调用另一个看起来像这样的函数:

void add_edge    (std::string origin, std::string destination, T value);

为了逐行拆分文本文件,我使用的是一个预定义的函数,它返回std::vector<std::string>,其中每个元素都可以通过这样做来访问:

input: hello, world, 2
std::vector<std::string> words = my_func::split(line, ',');
std::cout << words[0]; // outputs hello
std::cout << words[1]; // outputs world
std::cout << words[2]; // outputs 2

我想将三个words元素传递给add_edge,如下所示:add_edge(words[0], words[1], words[2]);但显然这会给我编译错误。

所以我试着做一个类型为T的类型转换,如下所示:

T value = (T) words[2]; 
add_edge(words[0],words[1],value);

这仍然给我编译错误。我一直在网上四处寻找,但我见过的任何东西都与我的情况相符。那么如何将words[2]转换为类型T,然后将其传递给add_edge

编辑:这是我得到的编译错误。

error: invalid cast from type '__gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type {aka std::basic_string<char>}' to type 'int'

解决方案是将words[2]转换为整数。老实说,我没有意识到这很容易,我几乎不知道模板类型,所以我肯定认为我必须做一些更棘手的事情。谢谢你的帮助。

0 个答案:

没有答案