如何动态设置类型
How do I dynamically set a type?
我一直在尝试编写从文本输入文件中读取和初始化图形的代码。
现在,图是一个模板类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++中的模板,它不是。
相关文章:
- 何时包含内置类型和运算符的标头?
- 基本类型与内置类型有什么区别C++
- 指内置类型的文字
- GLUT 问题:重新声明 c++ 内置类型'wchar_t'时出错
- 像自定义类一样构造的指针(内置类型)如何工作?
- 内置类型与用户定义的类型 C++
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- C++内置类型的基于类型的调度
- 函数重载:内置类型与用户定义类型
- 内置类型的构造函数初始化
- 内置类型的运算符函数
- 内置类型的重载运算符
- 在C++中,如何销毁内置类型?
- 为什么内置类型的对象上的溢出会导致异常/未定义的行为?
- 重新声明C++内置类型"wchar_t"Windows 10 过剩 CPP
- 可变类类型的丢弃值表达式的行为与可变内置类型的丢弃值表达式的行为不同
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 如何为内置类型添加成员功能,例如C 中的整数
- 是否允许使用标准库类型和内置类型过载操作员
- 将指针传递给在 C++ 中动态定义的内置类型