Search code examples
c++for-loopautoc++20

Range-based for loop with auto specifier combined with static_cast


Imaged that I have an std::vector of std::string, and I want to convert those std::string to std::string_view in range-based for loop:

auto v = std::vector<std::string>{"abc", "def", "ghi"};
for (std::string_view sv : v) {
    // do something with string_view
}

The above code is perfectly valid, but I want to remain the auto specifier to do that, how to do static_cast in one line range-based for loop like this? It seems like C++20 ranges can do this in a concise way, can someone give an example?

for (auto sv : v | static_cast<std::string_view>) {
    // do something with std::string_view
} 

Solution

  • Not that this is a good idea as written, but this might be a useful example of a more general transform concept (and an evil lambda trick):

    for(auto sv : v |
          views::transform([](std::string_view x) {return x;})) …