C++ Logo


Advanced search

Re: [std-proposals] find_integral_constant

From: Sébastien Bini <sebastien.bini_at_[hidden]>
Date: Wed, 28 Sep 2022 11:55:23 +0200

On Fri, Sep 23, 2022 at 8:00 PM Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>

> This could be spelled more ergonomically as:
> variant_.dynamic_emplace(deserialized_index, [](auto *p) {
> std::construct_at(p); deserialize(*p, stream);
> });
> where you just pass in the index you want to activate, and then the
> variant calls your visitor with an appropriate `T*` pointer for you to
> construct into.
> In other words:
> std::variant<int, std::string> v;
> v.emplace<1>("hello"); // legal in C++17, but requires a
> compile-time-constant template argument 1
> v.dynamic_emplace(1, [](auto *p) {
> if constexpr (std::same_as<decltype(p), std::string*>) {
> std::construct_at(p, "hello");
> }
> }); // silly, but legal, in C++Fantasy; permits a run-time-computed
> function argument 1
> Your utility to turn a runtime value into a compile-time integral_constant
> is certainly more general, but also vastly more expensive (one line of code
> could blow up into 256 or 65536 instantiations of that generic lambda's
> operator() template!) and I don't immediately see any really killer app for
> it. If you need this *only* for `variant`, then it seems like the
> generality isn't needed.
> my $.02,
> Arthur

I still found it useful on tuples as well. The real code is a bit more
complicated that the snipshot I gave as an example. There is no
`deserialize` function, instead there is a tuple of functors, where the
I-th functor of the tuple is used to serialize/deserialize the I-th element
of the variant if it holds it.

Hence the real code is more like:
std::variant_size_v<Variant>>(deserialized_index, [&](auto ID)
    auto& data = variant_.template emplace<ID>();
    auto& ser = std::get<ID>(serializers_);
    ser.deserialize(data, stream);

I don't see how std::find_integral_constant would be more expensive than
recursive_union::visit. You still need to instantiate the functor's
operator() for each type. Sure one could supply quite a large range to
find_integral_constant, but how would that be useful to anyone, unless they
already have thousands-large tuples or variants?

Received on 2022-09-28 09:55:36