带有gcc的通用lambdas mem_fn

时间:2018-12-08 10:50:01

标签: c++ gcc lambda

我正在尝试在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)

1 个答案:

答案 0 :(得分:2)

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