给定以下两个函数模板:
template <typename T>
void gorp(T*, std::function<void(T*)>)
{
}
template <typename T>
void klop(T*, std::function<void()>)
{
}
功能
klop()
如我所料,但gorp()
没有:
int x = 3;
//fails: candidate template ignored: could not match
//'function<void (type-parameter-0-0 *)>' against '(lambda at ...)
gorp( &x, [](int*){}); //1
//works
gorp<int>( &x, [](int*){}); //2
//fails: candidate template ignored: could not match
//'function<void (type-parameter-0-0 *)>' against 'void (^)(int *)'
gorp( &x, ^(int*){}); //3
//works
gorp<int>( &x, ^(int*){}); //4
//works
klop( &x, [](){}); //5
//works
klop( &x, ^(){}); //6
第 3、4、6 行使用 clang 块;第 1、2、5 行使用 lambdas.
注意调用
klop()
没有问题推断T
,但我必须帮助调用gorp()
.
我很茫然。
gorp()
弄清楚 T
不应该加倍容易吗?
它不会推断类型
T
,因为你没有传递std::function
。如果还需要转换,则类型推断不起作用。这确实有效:
gorp(&x, std::function<void(int*)>([](int*) {}));
使用普通函数指针也是如此:
template <typename T>
void gorp(T*, void(*)(T*))
{
}
gorp(&x, +[](int*) {}); // + converts captureless lambda to function pointer