0
#include <iostream>
#include <numeric>
#include <ranges>
#include <vector>
#include <string>
#include <string_view>

int main() {
    auto str = (
        std::views::iota(1)
        | std::ranges::views::take(5)
        | std::ranges::views::transform([](int x) -> std::string_view {
            return std::to_string(x) + "|";
        })
        | std::ranges::views::join
    );

    for (const char ch : str) {
        std::cout << ch;
    }

    return 0;
}

I'm new to functional programming in cpp. I want to generate first five natural numbers and translate them to string, then join them and print it.

If I use std::string for return type of lambda for transform, it throws many error on compile time. I thought that I should change it into std::string_view. I changed so, and it compiled without compile error. However, if I use std::string_view there, the lambda function returns only reference for string, and translated string that on stack memory is removed on memory when lambda ends. So, the program doesn't print anything.

How can I fix it?

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
lunuy lunuy
  • 429
  • 3
  • 7
  • *"it throws many error on compile time."* -- please include the first such error in your question so that the next person with the same issue can find this question by searching for the error message. – JaMiT Jan 05 '22 at 05:53

1 Answers1

5

If I use std::string for return type of lambda for transform, it throws many error on compile time.

What you have observed is a C++20 defect that has been resolved by P2328. If you use a newer compiler version that has already implemented P2328 (such as gcc-11.2), your code will be well-formed.

Before P2328, I think there is no simple solution in the standard.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90