我目前正在学习并行编程和元编程,并且我很难对捕获变量的 lambda 进行编译时检查。
假设我们有这样的代码:
#include <type_traits>
#include <functional>
#include <iostream>
int main(){
auto non_capture = [](){
std::cout<<"this lambda is not capturing!"<<std::endl;
};
auto capture = [&](){
std::cout<<"this lambda is capturing"<<std::endl;
};
//value is true for this one
static_assert(std::is_convertible<decltype(non_capture), std::function<void()>>::value, "message1");
//i need help for this
static_assert(is_lambda_that_captures<decltype(capture)>::value, "this is some error message");
}
Run Code Online (Sandbox Code Playgroud)
我需要帮助来定义is_lambda_that_captures类型特征,以便我可以传递第二个静态断言。我该怎么做?
拥有最新标准的解决方案是非常受欢迎的(当前最新的是 c++17):)
这是我的解决方案。它依赖于两个原则:
非捕获 lambda 可转换为函数指针。
所有 lambda 表达式均可转换为 std::function。
#include <type_traits>
#include <functional>
#include <iostream>
template<class T, class Ret, class...Args>
struct is_non_capture_lambda : std::is_convertible<T, Ret (*)(Args...)>
{
};
template<class T, class Ret, class...Args>
struct is_capture_lambda
{
static constexpr auto convertible = std::is_convertible<T, std::function<Ret(Args...)>>::value;
using type = bool;
static constexpr auto value = convertible && !is_non_capture_lambda<T, Ret, Args...>::value;
};
int main(){
auto non_capture = [](){
std::cout<<"this lambda is not capturing!"<<std::endl;
};
auto capture = [&](){
std::cout<<"this lambda is capturing"<<std::endl;
};
//value is true for this one
static_assert(is_non_capture_lambda<decltype(non_capture), void>::value, "message1");
//i need help for this
static_assert(is_capture_lambda<decltype(capture), void>::value, "this is some error message");
}
Run Code Online (Sandbox Code Playgroud)