【问题标题】:Accept and identify any type of input C++接受并识别任何类型的输入 C++
【发布时间】:2015-12-31 18:57:42
【问题描述】:

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

我的问题是:有什么方法可以通过std::cin(或任何其他输入法)接受任何类型的输入,然后根据输入的类型调用某些函数?

一些符合...逻辑的东西

cin >> data

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

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

谢谢!

【问题讨论】:

  • C++ Variant的可能重复
  • 读取为字符串,尝试转换为整数,如果成功(并且在转换中消耗了所有字符串)那么你有一个整数,否则它是一个字符串。我前段时间回答了这个问题,但似乎找不到我自己的重复答案。
  • 重载一个函数来获取不同的类型。为什么不试试呢?只需让每个重载的主体打印出赋予函数的每种类型。

标签: c++ validation input


【解决方案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::any 和 boost::variant。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2019-12-17
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多