2

这篇文章专门讨论 lambda 函数,特别是涉及到它们的ClosureType::operator ret(*)(params)(). 在文章中,该运算符称为“通用无捕获 lambda 用户定义转换函数模板”。

给定代码(自动转换为适当类型的函数指针):

#include <iostream>
#include <cstdlib>

#if 0

template< typename L, typename R, typename ...A >
constexpr
auto 
to_function_pointer(L l, R (L::*)(A...) const)
{
    return static_cast< R (*)(A...) >(l);
}

template< typename L, typename R, typename ...A >
constexpr
auto 
to_function_pointer(L l, R (L::*)(A...))
{
    return static_cast< R (*)(A...) >(l);
}

template< typename L >
constexpr
auto 
to_function_pointer(L l)
{
    return to_function_pointer(l, &L::operator ());
}

#endif

template< typename R, typename ...A >
constexpr
auto
to_function_pointer(R (* fp)(A...))
{
    return fp;
}

namespace
{

void f() { std::cout << __PRETTY_FUNCTION__ << std::endl; }

}

int main()
{
    to_function_pointer(f)();
    to_function_pointer(&f)();
    to_function_pointer([] () { std::cout << __PRETTY_FUNCTION__ << std::endl; })();
    to_function_pointer([] () mutable { std::cout << __PRETTY_FUNCTION__ << std::endl; })();
    return EXIT_SUCCESS;
}

#if 0代码中的函数to_function_pointer无法将 lambda 转换为相应的函数指针。这是否意味着提到的运算符是由explicit关键字“隐式”标记的?标准中有相应的条款吗?

4

0 回答 0