【问题标题】:Problem when checking whether std::any variable holds a std::string检查 std::any 变量是否包含 std::string 时出现问题
【发布时间】:2019-12-15 20:27:33
【问题描述】:

在 c++ 中,您可以比较两个 type_info 对象。

std::any 类。它有一个成员.type(),它还会返回一个type_info 对象,告诉你它包含的类型。我可以使用typeid(THE_TYPE) 并比较两者。

以下代码有效:

std::any x = 6;

if (x.type() == typeid(int)) {
    cout << "x is int";
}

但以下方法不起作用:

std::any x = "string literal";

if (x.type() == typeid(std::string)) {
    cout << "x is string";
}

我做错了什么?如何检查变量是否为字符串?

【问题讨论】:

    标签: c++ string types


    【解决方案1】:

    问题是,"string literal" 不是 std::string 类型,它是一个 c 风格的字符串,即 const char[15] 本身。而std::any 将其视为const char*。因此,如果您按以下方式更改条件,您将得到"x is string" 打印出来。

    if (x.type() == typeid(const char*))
    

    要解决此问题,您可以将 std::string 显式传递给 std::any

    std::any x = std::string("string literal");
    

    或使用literal

    using namespace std::string_literals;
    std::any x = "string literal"s;
    

    【讨论】:

      【解决方案2】:

      基本上,语句std::any x = “string literal”; 将“字符串文字”视为字符常量。所以 x 的类型是const char*。 要使代码按您的意愿工作,您可以将其更改为:

      std::any x = std::string(“string literal”);
      
      if (x.type() == typeid(std::string)) {
       cout << “x is string”;
      }
      

      这可能会解决您的问题,谢谢

      【讨论】:

        【解决方案3】:

        std::any x = “string literal”; 不存储std:: string。它存储了一个char const [15]

        我认为修复它的正确方法是确保存储 std::string。要么写:std::any x = std::string{ “string literal”};,要么写std::any x = “string literal”s;(最后一个需要使用using namespace std::string_literals;

        就个人而言,我也会考虑将std::string_view 放入其中,因为它不会为字符串分配内存。但是,它可能会使使用变得复杂。

        【讨论】:

          猜你喜欢
          • 2021-03-17
          • 2011-09-10
          • 1970-01-01
          • 2016-10-16
          • 2023-02-02
          • 2020-03-03
          • 1970-01-01
          • 1970-01-01
          • 2020-02-22
          相关资源
          最近更新 更多