我创建了一个模板化函数,我试图自动推导模板参数。
MCVE(编译它):
template<class Value, class Allocator>
void foo(const std::vector<Value, Allocator>& v, const std::function<void(const Value&)>& f)
{
}
int main()
{
vector<int> v;
foo<int>(v, [](const int&){}); //okay
//foo(v, [](const int&){}); //not okay
return 0;
}
我首先认为分配器无法被推导,但这似乎并不能解决问题。
我的下一个猜测是它与 std::function 的 lambda 有关,但不知道进一步的步骤。有人知道我需要做什么才能使这个推论有任何线索吗?
Ps:我知道“const int&”可能会变成“int”,但在实际代码中存在非标量数据类型。
模板参数推导发生在 Lambda 隐式转换为std::fucntion
.
类型推导不考虑隐式转换(上面列出的类型调整除外):这就是过载解析,这会在稍后发生。
模板参数的含义类型推导Value
在第二个函数参数上f
失败是因为从 lambda 到的隐式转换std::function
不予考虑。
正如您所展示的,您可以显式指定模板参数(以绕过模板参数推导)。或者您可以使用以下方法从推论中排除第二个参数std::type_identity将其声明为非推导上下文.
The 嵌套名称说明符(范围解析运算符左侧的所有内容::
)使用指定的类型合格的 ID:
e.g.
template<class Value, class Allocator>
void foo(const std::vector<Value, Allocator>& v, const std::function<void(const std::type_identity_t<Value>&)>& f)
{
}
LIVE
PS: std::type_identity从 C++20 开始支持;如果您使用的编译器不支持它,那么制作一个并不难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)