Home > Back-end >  When I use typeid() to judge a type, different type will compile error
When I use typeid() to judge a type, different type will compile error

Time:08-04

When I use typeid() to judge a type, different type will compile error.

This code can't compile successfully because the judge of typeid() is RTTI. How shall I modify this code?

error: no matching function for call to '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);
}

CodePudding user response:

Compiler will compile both branches no matter the condition, the C 17 solution is constexpr if

There is no reason to use typeid machinery for this, std::is_same_v from <type_traits> will do its job just fine:

if constexpr (std::is_same_v<std::string, T>) {
    res->push_back(str.substr(next_begin_pos, next_end_pos - next_begin_pos));
} else {
    std::istringstream is(
        str.substr(next_begin_pos, next_end_pos - next_begin_pos));
    is >> value;
    res->push_back(value);
}
  •  Tags:  
  • c
  • Related