gpt4 book ai didi

c++ - 英特尔编译器无法编译具有多个参数的可变 lambda 捕获

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:43 25 4
gpt4 key购买 nike

这是我能够想出的最小示例:

#include <utility>
template<class CB, class... ARGS>
void call_lam(CB&& cb, ARGS&&... args) {
auto lam = [&args...](auto&& callee) {
callee(std::forward<ARGS>(args)...);
};
lam(cb);
}

void exec(unsigned, int);

void foo() {
unsigned x = 25;
int y = 0;
call_lam(exec, x, y);
}

以上示例使用 CLang 和 gcc 编译,但使用 icc 17.0 失败(如 https://godbolt.org/g/tzMY6K 所示)。错误如下:

/usr/include/c++/5/bits/move.h(89): error: static assertion failed with "template argument substituting _Tp is an lvalue reference type"

static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"

^ detected during:

instantiation of "_Tp &&std::forward<_Tp>(std::remove_reference<_Tp>::type &&) [with _Tp=unsigned int &]" at line 5 of ""

instantiation of function "lambda [](auto &&)->auto [with =void (&)(unsigned int, int)]" at line 7 of ""

instantiation of "void call_lam(CB &&, ARGS &&...) [with CB=void (&)(unsigned int, int), ARGS=]" at line 15 of "" compilation aborted for (code 2)

Compiler exited with result code 2

玩这个例子,我发现:

  • 它必须是不同的类型作为exec 的参数。使用两个整数或单个参数时,错误消失
  • 通过将类型替换为其他内容(例如,std::string)并更改将参数传递给 exec 的方式(const& ) 可以将错误报告为其他内容,表示“无法匹配 std::move 的重载”。此时,它在 icc16 上也会失败。这是稍微修改过的代码:https://godbolt.org/g/qHrU6P

如果代码格式正确(正如我所相信的那样),除了用自定义仿函数替换 lambda(我不想这样做,因为我不想手动捕获具有适当引用的可变数量的参数通过元组)有人在这里看到任何解决方法吗?

最佳答案

我认为下面的代码将满足您的解决方法要求:

#include <utility>
#include <iostream>
#include <tuple>

template<class CB, class... ARGS>
void call_lam(CB&& cb, ARGS&&... args) {
auto lam = [](auto&&... args2){
return [&args2...](auto&& callee) {
callee(std::forward<std::tuple_element_t<0, std::decay_t<decltype(args2)>>>(std::get<0>(args2))...);
};}(std::forward_as_tuple(std::forward<ARGS>(args))...);
lam(cb);
}

struct A {
A() {
std::cout << "A()" << std::endl;
}
A(const A&) {
std::cout << "A(const A&)" << std::endl;
}
A(A&&) {
std::cout << "A(A&&)" << std::endl;
}
};

void exec(A &, A) {
}

int main() {
A a;
call_lam(exec, a, A());
}

关于c++ - 英特尔编译器无法编译具有多个参数的可变 lambda 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247582/

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