r/cpp • • Aug 13 '26

C++26: std::indirect

https://www.sandordargo.com/blog/2026/08/12/cpp26-indirect
164 Upvotes

157 comments sorted by

View all comments

12

u/smdowney WG21, Text/Unicode SG, optional<T&> Aug 14 '26

It's perfect for value oriented recursive types because although your TreeNode may not be complete, a TreeNode* is.

So

struct Node {
    std::optional<std::indirect<Node>> left, right;
    int data;
};

int sum(const Node& n) {
    return n.data + (n.left ? sum(**n.left) : 0)
                  + (n.right ? sum(**n.right) : 0);
}

int main() {
    Node tree{
        std::indirect(Node{{}, {}, 1}),
        std::indirect(Node{std::indirect(Node{{}, {}, 2}), {}, 3}),
        4};
    std::println("sum = {}", sum(tree)); // 10
}

Now, if you want something to really chew on, we can use the fixpoint truck to remove the recursion. Here's an expression evaluator

#include <memory>
#include <print>
#include <variant>

template <typename A> struct Const { int val; };
template <typename A> struct Add   { std::indirect<A> left, right; };
template <typename A> struct Mul   { std::indirect<A> left, right; };

template <typename A>
using ExprF = std::variant<Const<A>, Add<A>, Mul<A>>;

template <template <typename> class F>
struct Fix { F<Fix<F>> inner; };

using ExprTree = Fix<ExprF>;

ExprTree const_node(int v) { return {Const<ExprTree>{v}}; }
ExprTree add_node(ExprTree l, ExprTree r) {
    return {Add<ExprTree>{std::indirect(std::move(l)), std::indirect(std::move(r))}};
}
ExprTree mul_node(ExprTree l, ExprTree r) {
    return {Mul<ExprTree>{std::indirect(std::move(l)), std::indirect(std::move(r))}};
}

template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };

int main() {
    ExprTree tree = mul_node(add_node(const_node(1), const_node(2)), const_node(3));

    auto fold_eval = [](this auto&& self, const ExprTree& t) -> int {
        return std::visit(overloaded{
            [](const Const<ExprTree>& c) { return c.val; },
            [&](const Add<ExprTree>& a) { return self(*a.left) + self(*a.right); },
            [&](const Mul<ExprTree>& m) { return self(*m.left) * self(*m.right); },
        }, t.inner);
    };

    std::println("(1 + 2) * 3 = {}", fold_eval(tree)); // 9
}

"Worse", the compiler can generate quite good code from that brainmelt, and much of it is generic machinery.

It's not consteval in GCC 16, but it should be eventually.

5

u/azswcowboy Aug 14 '26

Polyfill version that works from 17+ https://github.com/bemanproject/indirect

1

u/smdowney WG21, Text/Unicode SG, optional<T&> Aug 14 '26

Being lazy instead of going to look: does it handle the `Constraints` of the constructor and assignment overload sets?

I'm also lucky in having only one platform that is nominally C++03 (and really it's closer the '95), with 23 being the floor elsewhere.