gpt4 book ai didi

c++ - 带有 gcc 的通用 lambdas mem_fn

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:19 25 4
gpt4 key购买 nike

我正在尝试将 lambda 转换为 C++ 中的 mem_fn

我遇到了 gcc 和通用 lambda 的问题。有谁知道是否可以为 gcc 做些什么?

#include <functional>

// Standard lambda
auto std_lambda = [](double x) -> double {
return 2. * x;
};


// generic lambda
auto generic_lambda = [](auto x) {
auto two = static_cast<decltype(x)>(2.l);
return two * x;
};



void test()
{
// convert lambdas to mem_fn
// this call works on gcc/clang/msvc
auto std_mem_fn = std::mem_fn(
& decltype(std_lambda)::operator() );

// convert lambdas to mem_fn
// this call works on clang/msvc
// but fails on gcc
auto generic_mem_fn = std::mem_fn(
& decltype(generic_lambda)::template operator()<double> );

// By the way, I would be interested to make the
// mem_fn instantiation code more similar
// for generic and template lambdas
}

Compiler Explorer 上测试此代码(适用于 clang、mscv,但不适用于 gcc)

最佳答案

这可能是 GCC 错误,因为如果您在构建 std::mem_fun 之前“使用”通用 lambda,它会编译。通过“使用”我的意思是例如调用 lambda 或单独存储 mem-fun 指针:

#include <functional>

auto generic_lambda = [](auto x) {
auto two = static_cast<decltype(x)>(2.l);
return two * x;
};

int main()
{
// call the lambda ...
generic_lambda(1.0);

// or retrieve the mem-fun ptr
auto unused = &decltype(generic_lambda)::template operator()<double>;

// now it compiles on GCC
auto generic_mem_fn = std::mem_fn(
& decltype(generic_lambda)::template operator()<double> );
}

参见 live example

因此您可以使用以下方法使其与 GCC 兼容:

auto ptr = &decltype(generic_lambda)::template operator()<double>;    
auto generic_mem_fn = std::mem_fn(ptr);

关于c++ - 带有 gcc 的通用 lambdas mem_fn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681778/

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