views:

42

answers:

1

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
}
+3  A: 

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! */ }
Johannes Schaub - litb