开发者

Passing a lambda to a template function on VC10

I wrote the following code on VC10. Calling f1 is okay, but on calling f2 the开发者_运维技巧 compiler showed an error. The difference between the two functions is only "template ", but the template type is actually not used. Why does the error occur?

#include <functional>

void f1( std::tr1::function<void()> f)
{
}

template <typename >
void f2( std::tr1::function<void()> f)
{
}

int main()
{
    f1( []{} );
    f2( []{} ); // Error C2783
}

Now I understand the error on the first code. How about the following code? Is it the error reason that the compiler can't decide the template type because lambda generates an internal anonymous class, but it is different from std::tr1::function?

#include <functional>

class MyClass
{
};

template <typename T>
void f2( std::tr1::function<void(T)> f)
{
}

int main()
{
    std::tr1::function<void(MyClass)> f= [](MyClass v){};

    f2( f );
    f2( [](MyClass v){} ); // C2784
}


This is not specific to lambdas at all. You need to tell the compiler what version of the template you want to call:

f2<int>([]{});
f2<float>([]{});

It doesn't matter whether you use them or not. It's like unused function parameters:

void f(int) { }
int main() { f(); /* error! */ }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜