无法推导出模板参数(向量, std::function)

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

我创建了一个模板函数,我试图自动推导出模板参数.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;
}

我首先认为Allocator不能被推导出来,但这似乎并不能解决这个问题.我的下一个猜测是它与std::function的lambda有关,但不知道进一步的步骤。有谁知道我需要做什么才能使这个推导出来?

Ps: 我知道 "const int& "可以变成 "int",但在实际代码中,那里有一个非标量数据类型。

c++ templates c++14
1个回答
3
投票

模板论证演绎 不考虑隐式转换。

类型扣减不考虑隐式转换(除了上面列出的类型调整):这是由 过载解决办法,这在后面发生。

然后对模板参数进行类型演绎 Value 在第2个函数参数上 f 失败,因为从lambda隐式转换为 std::function 不被考虑。

正如你所展示的那样,你可以明确地指定模板参数(以绕过模板参数的扣减)。或者你也可以通过使用 std::type_identity 宣布为 非演绎语境.

嵌套名称说明者 (范围解析运算符左边的所有内容) ::)的类型,该类型是用 合格证:

例如

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开始支持;如果你使用的编译器不支持它,不难制作一个。

© www.soinside.com 2019 - 2024. All rights reserved.