c++ - 如何在 C++ 的模板定义中使用 lambda?

标签 c++ templates lambda

这是我正在努力实现的一个简单示例。甚至可以将 lambda 传递给模板函数吗?

头文件

class my_impl {
public:
    template<typename F> void do_something(F && f);
};

CPP 文件

// .cpp file
template<typename F> my_impl::do_something(F && f)
{
    // ... implementation
}

template void my_impl::do_something<std::string &&>(std::string &&); // OK
template void my_impl::do_something<???>(???); // what goes here for lambda?

// used like this
my_impl impl;
impl.do_something( "123" );
impl.do_something( []() { 
   ...
} );

最佳答案

lambda 是编译器生成的唯一内部类型的实例。

您可以使用调试器亲眼看到这一点。例如,给定以下简短的测试代码片段:

class my_impl {
public:
    template<typename F> void do_something(F && f);
};

template<typename F> void my_impl::do_something(F && f)
{
}

int main()
{
    my_impl m;

    m.do_something( []() {} );
}

使用 gcc 5.3,单步执行调试器,观察到以下结果:

main () at t.C:22
22      m.do_something( []() {} );
(gdb) s
my_impl::do_something<main()::<lambda()> >(<unknown type in /tmp/t, CU 0x0, DIE 0x23e>) (this=0x7fffffffe44d, f=<unknown type in /tmp/t, CU 0x0, DIE 0x23e>)
    at t.C:9

请注意,gdb 将模板实例报告为类型 my_impl::do_something<main()::<lambda()> > .编译器生成了一个内部伪类型 main()::<lambda()>对于 lambda 类型。当然,您不能引用这样的类型。

我没有看到引用 lambda 内部类型的方法。

关于c++ - 如何在 C++ 的模板定义中使用 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373292/

相关文章:

c++ - 让 Juce 工作 (Windows)

c++ - CMAKE_<LANG>_LINK_EXECUTABLE 是否支持生成器表达式?

c++ - 如何在 C++/CX 类之间传递旧版 C++ void 指针?

c++ - 可移植行尾(换行)

调用模板化内部类静态成员函数的 C++ 语法?

c++ - 使用变量模板调用可变参数函数

templates - TYPO3 流体 : How is it possible to use conditions and variables outside of <f:section> to make the layout dynamic?

c++ - 在 C++ Lambda 表达式中,为什么人们更喜欢按值捕获而不是作为参数传递?

c++ - 为什么在 C++20 中使用 `std::bind_front` 而不是 lambda?

scala - 使用下划线构造 lambda 表达式