c++ - 如何在 VS2010 中将 lambda 降级为函数指针?

标签 c++ visual-studio-2010 visual-c++ c++11

这是我失败的尝试:

#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){})
    };
}

最佳答案

在你说的评论中,

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)

在这种情况下,您可以使用局部结构并在其中定义一个静态函数。 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);
}

它很方便 - 或多或少类似于 C++11 lambda。您可以在本地定义静态成员函数,并将其传递给其他函数。

关于c++ - 如何在 VS2010 中将 lambda 降级为函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511046/

相关文章:

c++ - 将 OpenSSL 静态库添加到 vc++ 项目

c++ - STL 容器的二进制兼容性

c++ - autotools undefined reference 错误

visual-studio-2010 - 如何仅使用一组解决方案/项目文件同时针对 Win32 和 x64 平台?

C++ Visual Studio .exe 消失

c++ - 如何调试 Visual Studio 环境变量的使用?

c++ - VS2010 中的 "redefinition; different type modifier"

c++ - 将自定义类添加到 Qt 项目

c++ - boost::atomic 真的可以通过减少多线程系统调用(在互斥/信号量中)的开销来 boost 性能吗?

debugging - 如何在VC++ 6中调试 "debug assertion failure"