gpt4 book ai didi

c++ - 为什么编译器不能推导模板模板参数?

转载 作者:行者123 更新时间:2023-12-01 14:35:45 25 4
gpt4 key购买 nike

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

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<vector<string>>(v)

最佳答案

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

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

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

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

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());

关于c++ - 为什么编译器不能推导模板模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63439263/

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