1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // UNSUPPORTED: c++03, c++11, c++14, c++17 10 // UNSUPPORTED: libcpp-no-concepts 11 // UNSUPPORTED: gcc-10 12 // UNSUPPORTED: libcpp-has-no-incomplete-ranges 13 14 // Some basic examples of how transform_view might be used in the wild. This is a general 15 // collection of sample algorithms and functions that try to mock general usage of 16 // this view. 17 18 #include <ranges> 19 20 #include <cctype> 21 #include <functional> 22 #include <list> 23 #include <numeric> 24 #include <string> 25 #include <vector> 26 27 #include <cassert> 28 #include "test_macros.h" 29 #include "test_iterators.h" 30 #include "types.h" 31 32 template<class T, class F> 33 concept ValidTransformView = requires { typename std::ranges::transform_view<T, F>; }; 34 35 struct BadFunction { }; 36 static_assert( ValidTransformView<ContiguousView, Increment>); 37 static_assert(!ValidTransformView<Range, Increment>); 38 static_assert(!ValidTransformView<ContiguousView, BadFunction>); 39 40 template<std::ranges::range R> 41 auto toUpper(R range) { 42 return std::ranges::transform_view(range, [](char c) { return std::toupper(c); }); 43 } 44 45 unsigned badRandom() { return 42; } 46 47 template<std::ranges::range R, class Fn = std::plus<std::iter_value_t<R>>> 48 auto withRandom(R&& range, Fn func = Fn()) { 49 return std::ranges::transform_view(range, std::bind_front(func, badRandom())); 50 } 51 52 template<class E1, class E2, size_t N, class Join = std::plus<E1>> 53 auto joinArrays(E1 (&a)[N], E2 (&b)[N], Join join = Join()) { 54 return std::ranges::transform_view(a, [&a, &b, join](auto& x) { 55 auto idx = (&x) - a; 56 return join(x, b[idx]); 57 }); 58 } 59 60 int main(int, char**) { 61 { 62 std::vector vec = {1, 2, 3, 4}; 63 auto sortOfRandom = withRandom(vec); 64 std::vector check = {43, 44, 45, 46}; 65 assert(std::equal(sortOfRandom.begin(), sortOfRandom.end(), check.begin(), check.end())); 66 } 67 68 { 69 int a[4] = {1, 2, 3, 4}; 70 int b[4] = {4, 3, 2, 1}; 71 auto out = joinArrays(a, b); 72 int check[4] = {5, 5, 5, 5}; 73 assert(std::equal(out.begin(), out.end(), check)); 74 } 75 76 { 77 std::string_view str = "Hello, World."; 78 auto upp = toUpper(str); 79 std::string_view check = "HELLO, WORLD."; 80 assert(std::equal(upp.begin(), upp.end(), check.begin(), check.end())); 81 } 82 83 return 0; 84 } 85