Is this use of the upcoming C++20 std::span
correct and with no overhead to wrap up the command line arguments?
#include <iostream>
#include <span>
int main(int argc, const char* argv[])
{
for (auto s : std::span { argv, static_cast<std::size_t>(argc) })
std::cout << s << std::endl;
}
If it is correct, could I go futher and use with std::string_view
?
If you use ()
instead of {}
you don't need the really verbose cast:
std::span(argv, argc)
This gives you a range of char const*
. You can convert those to string_view
using transform
. This has some overhead because you need to do a bunch of strlen
s:
std::span(argv, argc)
| std::views::transform([](char const* v){ return std::string_view(v); })
For stuff like this, I have a function object that performs casting, which is pretty easy to write, so this could be:
std::span(argv, argc)
| std::views::transform(static_cast_<std::string_view>)