为什么这个C++函数模板无法推断出模板类型?

问题描述 投票:0回答:1

给定以下两个函数模板:

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
不应该加倍容易吗?

c++ templates lambda type-inference
1个回答
0
投票

它不会推断类型

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
© www.soinside.com 2019 - 2024. All rights reserved.