David
David

Reputation: 28178

How can I degrade a lambda to a function pointer in VS2010?

Here's my failed attempt:

#define decltype(...) std::identity<decltype(__VA_ARGS__)>::type

template<typename T>
auto* degrade(const T& f) -> decltype(&T::operator())
{
    return &T::operator();
} 

int main()
{
    std::array<void(int), 1> stuff =
    {
        degrade([](int){})
    };
}

Upvotes: 3

Views: 278

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361362

In the comment you said,

VS2010 doesn't support it. - Nawaz the library I'm using has a method that takes a function pointer, It would be slightly cleaner to use a lambda (it's not a big deal, but I wanted to see if it was possible in VS2010)

In that case, you could use local struct and define a static function in that. Something like this (well if it helps you):

#include <iostream>

void call(void (*f)(int))
{
    for(int i = 0 ; i < 10 ; i++)
         f(10 * i);
}

int main() 
{
    struct local
    {
        static void print(int i) { std::cout << i << std::endl; }
    };
    call(&local::print);
}

It is handy - more or less like C++11 lambda. You can define a static member function locally, and pass around it to other functions.

Upvotes: 1

Related Questions