C++ Type erasure with traits

273 Views Asked by At

I wanted to know that this is possible to make an erased type that conforms to a trait like this one :

template<class T>
using read_t = std::conditional_t<true,
    decltype(std::declval<T>().Read(uint16_t{})),
    std::integral_constant<uint8_t (T::*)(uint16_t), &T::Read>>;

and use it like this ?

using any_readable_t = any<read_t>; 
auto test(any_readable_t &r) -> uint8_t {
     return r.Read(0);
}
1

There are 1 best solutions below

2
On

Without any external library, there's a lot of work that needs to be done to achieve what you want. Using Louis Dionne's dyno:

DYNO_INTERFACE(Readable,
    (read, uint8_t (uint16_t))
);

auto test(Readable& r) -> uint8_t {
    return r.read(0);
}