How to use C++20 ranges and views

According to this page, the “One Ranges Proposal” is ready in Clang 15. I downloaded a binary release of clang+llvm from github here.

But, trying an example from cppreference.com:

#include <iostream>
#include <ranges>
#include <algorithm>

int main() {
    for (int i : std::ranges::iota_view{1, 10})
        std::cout << i << ' ';
    std::cout << '\n';
 
    for (int i : std::views::iota(1, 10))
        std::cout << i << ' ';
    std::cout << '\n';
}

With compile command:

% SYSR=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk
% clang++ -isysroot $SYSR -std=c++2b hello.cc
hello.cc:7:40: error: expected ')'
    for (int i : std::ranges::iota_view{1, 10})
                                       ^
hello.cc:7:9: note: to match this '('
    for (int i : std::ranges::iota_view{1, 10})
        ^
hello.cc:7:31: error: no member named 'iota_view' in namespace 'std::ranges'
    for (int i : std::ranges::iota_view{1, 10})
                 ~~~~~~~~~~~~~^
hello.cc:11:23: error: no member named 'views' in namespace 'std'
    for (int i : std::views::iota(1, 10))
                 ~~~~~^
3 errors generated.

Is there a compiler flag to turn it on?

There is -fexperimental-library. Search for it in the release notes for further details:
https://releases.llvm.org/15.0.0/projects/libcxx/docs/ReleaseNotes.html

1 Like

Awesome, thank you!

Here’s are command I used to compile the test program. (On macOS 13.0 Ventura).

SYSR=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk
CLANG_15=/Users/rob/Dev/clang+llvm-15.0.1-x86_64-apple-darwin
$CLANG_15/bin/clang++ -isysroot $SYSR -std=c++2b hello.cc -fexperimental-library -L $CLANG_15/lib -o hello -fuse-ld=lld

It runs:

% ./hello                                                                                                                
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 

But I’m not sure if it’s linking against the libc++ in Clang 15, or the system’s libc++.

% otool -L hello
hello:
	@rpath/libc++.1.dylib (compatibility version 1.0.0, current version 1.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1311.100.3)

I don’t know how to find rpath. This returns nothing: otool -l hello | grep RPATH.

Me neither, but Apple is probably not shipping the ranges yet. The release notes talked about an archive and statically linking.

SYSR=`xcrun --sdk macosx12.3 --show-sdk-path`

is shorter.