【问题标题】:Why compiler cannot deduce template template argument?为什么编译器不能推断模板模板参数?
【发布时间】:2020-08-16 16:23:17
【问题描述】:

我想编写一个函数,它接受任何类型的通用容器并打印它。
让我们暂时离开它不适用于某些关联容器并专注于这个问题:

template<template<typename> typename Cont, typename T>
void print(const Cont<T>& cont)
{
   for (const auto it : cont)
   {
      cout << it << " ";
   }
   cout << endl;
}

int main()
{
   vector<string> v;
   print(v);
}

错误状态:

error C2672: 'print': no matching overloaded function found    
error C3207: 'print': invalid template argument for 'Cont', class template expected

谁能解释一下为什么编译器不能在这里推断出类型?
即使我明确声明print&lt;vector&lt;string&gt;&gt;(v)?

【问题讨论】:

  • 您不需要模板模板参数。 template &lt;typename Cont&gt; void print(const Cont&amp; cont) {...} 也可以。
  • 如果你看到例如this std::vector reference 你会看到它有 两个 模板参数,而不是你指定的一个。并且不同的标准容器有不同数量的模板参数。

标签: c++ c++11 templates function-templates template-templates


【解决方案1】:

std::vector 有多个类模板参数。

template<
    class T,                // -----------> you have mentioned!
    class Allocator = std::allocator<T>  // -----> this didn't!
> class vector;

但是你只提供了一个。这就是没有匹配重载编译器错误的原因。

为了解决这个问题,您需要在模板模板 arg 中提供可变参数 args。

template<template<typename...> typename Cont, typename T>
//       ^^^^^^^^^^^^^^^^^^^^
void print(const Cont<T>& cont)
{
   for (const auto& it : cont) {
      std::cout << it << " ";
   }
   std::cout << std::endl;
}

(See a demo)


但是,您可以简单地做到这一点

template <typename Cont>
void print(const Cont& cont) 
{ 
   // ...
}

或者像标准的方式,通过the begin and end iterator of the container to the function

#include <algorithm>  // std::copy
#include <iterator>   // std::iterator_traits

template<typename Iterator>
constexpr void print(const Iterator begin, const Iterator end) noexcept
{
   using ValueType = typename std::iterator_traits<Iterator>::value_type;
   std::copy(begin, end, std::ostream_iterator<ValueType>(std::cout, " "));
   std::cout << "\n";
}

然后这样称呼它

print(v.begin(), v.end());

【讨论】:

  • 或者干脆直接去掉模板模板参数,改成template &lt;typename Cont&gt; void print(const Cont&amp; cont) {...}
  • 除非他出于某种未包含在 MCE 中的原因需要 T。这通常是模板模板参数的原因,但标准类型通常提供解决方法
  • @Swift-FridayPie 即便如此,也可以通过typename Cont::value_type 或decltype(*std::begin(cont)) 获得。与 range-for 循环本身相比,后者尤其不需要来自 Cont 的任何支持。
  • @IgorTandetnik 是的,就是这么想的。我倾向于将这些添加到我的创作中 - 自定义类型也是如此,但每个人都有自己的风格。下一刻我看到有人问我为什么要添加这些声明,然后他们很乐意使用上面的模式而不是嵌套类型
【解决方案2】:

std::vector 定义为

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

std::vector 是一个有两个模板参数的类模板。不匹配 函数的模板模板参数。

改成

template <typename Cont>
void print(const Cont& cont) 
{
    for (const auto& elem : cont) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
}

如果有必要,您可以从容器中推断出T。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2015-09-23
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多