Zach Saw
Zach Saw

Reputation: 4378

Inline lambda expression causes compiler error

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)
}

Why does it only fail when the lambda expression is written inline as an argument to Foo?

Upvotes: 1

Views: 279

Answers (1)

ForEveR
ForEveR

Reputation: 55887

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

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

Lambda is temporary. Don't try bind temporary to reference. Use value, or const-reference or rvalue-reference.

Upvotes: 5

Related Questions