Gukki5
Gukki5

Reputation: 517

Get Type of Capture Lambda at Compile Time

I'm trying to create a class static map of capture lambdas, but having some difficulty getting the type at compile time, to feed into the map template.

this is the lambda signature...

[=] (const uint8_t *buffer, const size_t bufferSize) -> void 
                                                         { 
                                                            //stuff 
                                                         };

And I'm trying to store in a map like so...

constexpr static auto generateExampleLambda(void) {

   auto lambda = [=] (const uint8_t *buffer, const size_t bufferSize) -> void 
                                                         { 
                                                            //stuff 
                                                         };

   return lambda;
}

constexpr static inline auto exampleLambda = generateExampleLambda();
constexpr typedef decltype(exampleLambda) LambdaType;
static inline std::unordered_map<uint16_t, LambdaType> callbacks;

But obviously this doesn't compile. I've got it working with no capture, but of course that's the easy case lol.

Upvotes: 0

Views: 152

Answers (1)

max66
max66

Reputation: 66230

Unfortunately, every single lambda has his type.

To make it evident, you can verify that

auto l1 = []{};
auto l2 = []{};

static_assert( false == std::is_same_v<decltype(l1), decltype(l2)>, "!" );
// ............^^^^^

So I don't think it's possible to create a map for different lambdas with the type of the lambda.

The best I can imagine is insert the lambdas (more than one) in some std::function<void(const uint8_t, const size_t)> and make callbacks a

std::unordered_map<uint16_t, std::function<void(const uint8_t, const size_t)>>

Upvotes: 2

Related Questions