gpt4 book ai didi

C++ lambda 捕获约束

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:40 24 4
gpt4 key购买 nike

是否可以限制作为参数给定的 lambda 的捕获类型?
例如,是否可以只采用不通过引用捕获任何内容的 lambda?

template <typename F>
void f(const F& lambda) // F must be a lambda that do not capture by ref
{
:::
}

最佳答案

MSalters 指出“非捕获 lambda 可以转换为指向函数的指针”。这是什么意思? lambda 对象将匹配指向函数参数类型的指针。

将 lambda 类型转换为指向函数的指针是很棘手的。这是我对合规实现的尝试。这有点骇人听闻。

#include <type_traits>

template< typename fn >
struct ptmf_to_pf;

template< typename r, typename c, typename ... a >
struct ptmf_to_pf< r (c::*) ( a ... ) const >
{ typedef r (* type)( a ... ); };

// Use SFINAE to hide function if lambda is not convertible to function ptr.
// Only check that the conversion is legal, it never actually occurs.

template< typename lambda >
typename std::enable_if< std::is_constructible<
typename ptmf_to_pf< decltype( &lambda::operator() ) >::type,
lambda >::value >::type
f( lambda arg ) {
arg( "hello " );
arg( "world\n" );
}

#include <iostream>

int main() {
int x = 3;
f( []( char const *s ){ std::cout << s; } ); // OK
f( [=]( char const *s ){ std::cout << s; } ); // OK
f( [=]( char const *s ){ std::cout << s << x; } ); // error
}

这不会接受函数指针作为直接参数,因为模板参数需要解析为仿函数。您可以通过为接受指向函数类型的指针的 ptmf_to_pf 提供专门化来做到这一点。

此外,如演示所示,它不会接受按值和引用捕获任何内容的 lambda。在 C++ 中无法使限制如此具体。

关于C++ lambda 捕获约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9668213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com