admin管理员组

文章数量:1399490

Alright, so I’m messing around with Boost.Hana and trying to do something kinda cursed: compile-time type erasure. I wanna store a bunch of different types in a hana::tuple and call methods on them without knowing their exact type—but also without using virtual functions or heap allocation. Just pure constexpr wizardry.

Most type erasure tricks (std::any, std::function, inheritance) are runtime-based, but I wanna keep everything in compile-time land. Ideally, I want some generic wrapper where I can throw in any type and still be able to call a common interface on it.

Here’s what I got so far:

#include <boost/hana.hpp>
#include <iostream>

namespace hana = boost::hana;

struct TypeA { void foo() const { std::cout << "A\n"; } };
struct TypeB { void bar() const { std::cout << "B\n"; } };

constexpr auto container = hana::make_tuple(TypeA{}, TypeB{});

constexpr auto call_operation = hana::overload(
    [](const TypeA& a) { a.foo(); },
    [](const TypeB& b) { b.bar(); }
);

// This works, but hardcoding overloads ain't it. 
// Need something more generic and scalable.

The actual question:

  1. Is there a way to erase types at compile-time while keeping a unified interface, fully constexpr?

  2. Can I pull off compile-time "duck typing" in Hana where I don’t have to list out every overload manually?

  3. Any metaprogramming sorcery in Hana that lets me implicitly resolve method calls without me explicitly specifying the type?

本文标签: cHow do I pull off constexpr type erasure with BoostHana (no virtualsno heap)Stack Overflow