gpt4 book ai didi

c++ - 模板的模板的参数类型推导规则是什么?

转载 作者:行者123 更新时间:2023-12-02 01:24:35 26 4
gpt4 key购买 nike

我有三个使用模板的函数:

template <template <typename...> class ContainerType, typename ItemType>
bool has_item(ContainerType<ItemType> items, ItemType target_item)
{
// ...
}

template <template <typename...> class ContainerType, typename ItemType>
ContainerType<ItemType> filter(ContainerType<ItemType> items, const std::function <bool (ItemType)>& f)
{
// ...
}


template <template <typename...> class ContainerType, typename ItemType>
bool is_vector(ContainerType<ItemType> items)
{
// ...
}

我以为编译器可以成功推断出参数类型,但似乎无法推断出第二个参数类型。

    std::vector<int> v = {1, 2, 3, 4, 5};
std::cout << has_item(v, 1) << std::endl; // OK

auto less_four = [](int x) { return x < 4; };
std::vector<int> v2 = filter<std::vector, int>(v, less_four); // Can not be deduced automatically by compiler

std::cout << is_vector(v2) << std::endl; // OK

( Here 是演示)

这三个函数有什么区别,导致编译器无法自动推导类型?

最佳答案

因为对于第二个,ItemType 的模板参数推导在第二个函数参数上失败;模板参数推导中不会考虑隐式转换(从 lambda 到 std::function)。

您可以使用std::type_identity (C++20 起) 从模板实参推导中排除第二个函数形参。例如

template <template <typename...> class ContainerType, typename ItemType>
ContainerType<ItemType> filter(ContainerType<ItemType> items, const std::function <bool (std::type_identity_t<ItemType>)>& f)
{
// ...
}

您还可以添加另一个模板参数并停止使用 std::function

关于c++ - 模板的模板的参数类型推导规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75119034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com