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:
Is there a way to erase types at compile-time while keeping a unified interface, fully constexpr?
Can I pull off compile-time "duck typing" in Hana where I don’t have to list out every overload manually?
Any metaprogramming sorcery in Hana that lets me implicitly resolve method calls without me explicitly specifying the type?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744212720a4563411.html
评论列表(0条)