Nov 13, 2025

[C++][concepts] compound requirements trick

won't work after clang 16.0.0 which its more stricter, which using greedy deduction for `Any<Idxs> auto... _`
However, due to this kind of usage, C++ 26 has pack_indexing

#include <utility> // index sequence
#include <iostream> // for demo only

template<typename, size_t> concept Any = true;

auto invoke_with_last_arg(auto f, auto... args) {

    return [&]<size_t... Idxs>(std::index_sequence<Idxs...>) {
        // compound requirements, Any<Idxs> is assigned as: 
        // Any<decltype(_), size_t>
        return [&](Any<Idxs> auto... _, auto last) {
            return f(last);
        }(args...);
    }(std::make_index_sequence<sizeof...(args)-1>{});

}

void demo(auto... args) {
    invoke_with_last_arg(
        [](auto last_arg) { std::cout << last_arg << std::endl; },
        args...
    );
}

int main() { demo(3.14, 42, "hello world"); }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.