【问题标题】:Inline lambda expression causes compiler error内联 lambda 表达式导致编译器错误
【发布时间】:2012-08-01 02:01:48
【问题描述】:
template <typename T, typename Y, typename... Args>
class Bar
{
    T& t;
public:
    Bar(T& t) : t(t) { }
};

template <typename T, typename... Args>
void Foo(T &function) { new Bar<T, void, Args...>(function); }

int main()
{
    auto foo = [] { };
    Foo(foo); // ok

    Foo([] { }); // fails (tested on GCC 4.5.3)
}

为什么只有将 lambda 表达式作为 Foo 的参数内联写入时才会失败?

【问题讨论】:

    标签: c++ gcc lambda c++11


    【解决方案1】:
    template <typename T, typename... Args>
    void Foo(T &function) { new Bar<T, void, Args...>(function); }
    
    Foo([] { }); // fails (tested on GCC 4.5.3)
    

    Lambda 是临时的。不要尝试将临时绑定到引用。使用值,或 const-reference 或 rvalue-reference。

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2011-07-15
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      相关资源
      最近更新 更多