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

ラムダ式が Foo の引数としてインラインで記述されている場合にのみ失敗するのはなぜですか?

4

1 に答える 1

5
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 を使用します。

于 2012-08-03T03:06:38.540 に答える