【问题标题】:What is the argument type deduction rule for template of template?template of template 的参数类型推导规则是什么?
【发布时间】: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

标签: c++ templates


【解决方案1】:

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

您可以使用 std::type_identity 从模板参数推导中排除第二个函数参数。例如。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2018-07-06
    • 2017-09-23
    • 2010-11-07
    相关资源
    最近更新 更多