【问题标题】:When I use typeid() to judge a type, different type will compile error当我使用 typeid() 判断一个类型时,不同的类型会编译错误
【发布时间】:2022-08-03 17:37:02
【问题描述】:

当我使用 typeid() 判断一个类型时,不同的类型会编译错误。

这段代码无法编译成功,因为typeid()的判断是RTTI。我该如何修改这段代码?

错误:没有匹配函数调用\'std::vector<int>::push_back(std::basic_string<char>)\'

template <typename T>
void SplitOneOrMore(const std::string& str, std::vector<T>* res, const std::string& delimiters) {
  T value;
  std::string::size_type next_begin_pos = str.find_first_not_of(delimiters, 0);
  std::string::size_type next_end_pos = str.find_first_of(delimiters, next_begin_pos);
  while (std::string::npos != next_end_pos || std::string::npos != next_begin_pos) {
    if (typeid(std::string) == typeid(T)) {
      res->push_back(str.substr(next_begin_pos, next_end_pos - next_begin_pos));    // when T is int, this line will compile error.
    } else {
      std::istringstream is(str.substr(next_begin_pos, next_end_pos - next_begin_pos));
      is >> value;
      res->push_back(value);
    }
    next_begin_pos = str.find_first_not_of(delimiters, next_end_pos);
    next_end_pos = str.find_first_of(delimiters, next_begin_pos);
  }
}

TEST(SplitFixture, SplitOneOrMoreIntTest) {
  std::vector<int> ans;
  SplitOneOrMore<int>(\"127.0.0.1\", &ans, \".\");
  EXPECT_EQ(ans.size(), 4);
  EXPECT_EQ(ans[0], 127);
  EXPECT_EQ(ans[1], 0);
  EXPECT_EQ(ans[2], 0);
  EXPECT_EQ(ans[3], 1);
}
  • if 的所有分支都必须有效。 ->constexpr if

标签: c++


【解决方案1】:

无论条件如何,编译器都会编译两个分支,解决方案是constexpr if

没有理由为此使用typeid 机器,来自&lt;type_traits&gt;std::is_same_v 会很好地完成它的工作:

   if constexpr (std::is_same_v<std::string, T>) {
      res->push_back(str.substr(next_begin_pos, next_end_pos - next_begin_pos));    // when T is int, this line will compile error.
    } else {
      std::istringstream is(str.substr(next_begin_pos, next_end_pos - next_begin_pos));
      is >> value;
      res->push_back(value);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    相关资源
    最近更新 更多