【发布时间】:2023-01-14 23:35:57
【问题描述】:
我有三个使用模板模板的函数:
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 是演示)
这三个函数有什么区别,导致编译器无法自动推导类型?
【问题讨论】:
-
lambda 不是
std::function。