【问题标题】:generic lambdas mem_fn with gcc带有 gcc 的通用 lambdas mem_fn
【发布时间】:2018-12-08 20:21:03
【问题描述】:

我正在尝试在 C++ 中将 lambda 转换为 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)

【问题讨论】:

  • @MatthieuBrucher:我正在研究如何提取 lambda 类型的概念证明。见github.com/pthom/…

标签: c++ gcc lambda


【解决方案1】:

这可能是一个 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);

【讨论】:

  • 感谢非常的彻底调查!
猜你喜欢
  • 2016-11-27
  • 1970-01-01
  • 2018-03-28
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2017-03-18
  • 1970-01-01
相关资源
最近更新 更多