接受并识别任何类型的输入C ++

时间:2015-10-03 18:52:17

标签: c++ validation input

我试图编写一个创建链表的简单C ++程序。我想使这个列表能够在其容器中存储任何类型的数据。但是,我意识到我的主要问题是能够接受任何类型的输入并存储它。例如,如果变量std::cin存储为string类型,则只接受字符串,并且必须在程序编译之前定义此变量。

我的问题是:有没有办法接受任何类型的输入std::cin(或任何其他输入法),然后根据输入的类型调用某些函数?

沿着......的逻辑的东西。

cin >> data

if (data.type == string)
{
    cout << "data's type: string"
}

if (data.type == int)
{
    cout << "data's type: int"
}

谢谢!

1 个答案:

答案 0 :(得分:1)

C ++(主要)静态类型。也就是说,变量的类型必须在编译时是已知的,并且不能在运行时改变,例如,取决于一些用户输入。

这个规则的一个例外是多态类:当你有一个带有virtual成员函数的基类时,就会有一种方法(很可能是一个指针作为该类所有实例的成员)区分该类的子类(和它自己):

struct Base {
  virtual ~Base() {}
};
struct SubA : public Base {};
struct SubB : public Base {};

// ...

Base const & instance = SubA{};
try {
  SubA const & as_subA = dynamic_cast<SubA const &>(instance);
  // The instance is a SubA, so the code following here will be run.
} catch (std::bad_cast const &) { /* handle that somehow */ }

使用此机制,或者最好是虚拟函数本身,您可以根据实例的动态类型具有不同的行为,这只在运行时才知道。

C ++是一种灵活的语言,你当然可以自己实现类似的东西:

struct Thing {
  enum class Type {
    Integer, String, Vector
  } type;
  union {
    int integer;
    std::string string;
    std::vector<int> vector;
  } data;
  // Plus a lot of work in constructors, destructor and assignment, see rule of 5
};

使用类似这样的东西可以让对象具有动态性质的“类型”,并且可以根据对象在运行时实际具有的类型来执行不同的操作。

但是当然你不需要自己编写(though its not that hard),有很多实现,例如boost::anyboost::variant