STL 容器在函数中作为模板参数,在调用中出错



不明白什么是wrogn的代码,第二个函数定义或在main中调用这个函数? 我认为,但不确定,调用中的问题,因为没有调用代码编译得很好。编译器 gcc

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
void show_element(T ob)
{
cout << ob << " ";
}
template<template<class> class S, class T>
void show_sequence(S<T> sequence)
{
for_each(sequence.begin(), sequence.end(), show_element<T>);    
}
int main(int argc, char const *argv[])
{
std::vector<int> v(20, 0);
//here the problem
show_sequence<std::vector<int>, int>(v);
return 0;
}

>std::vector不是一个参数的模板,它也采用分配器类型。您可以将其用作vector<T>,因为第二个参数具有默认值 (std::allocator<T>(。

正如它所写的那样,您的模板函数不能接受任何标准容器,因为在我的头顶上,没有一个只接受单个类型参数。

一种有效的方法,不需要知道容器需要多少个模板参数,是接受容器类型(不是模板(,并从容器类型中收集值类型

template<class Seq>
void show_sequence(Seq const& sequence)
{
typedef typename Seq::value_type T;
for_each(sequence.begin(), sequence.end(), show_element<T>);    
}

所有标准容器都有一个value_type成员,因此这将适用于其中任何一个。此外,它将与任何从标准库中获取提示的容器一起使用。

问题是std::vector是一个模板,而std::vector<int>是一个类型。

当您为函数提供第二个类型时,您正在提供一种类型而不是模板。

因此,您可以将函数重写为:

template<class S>
void show_sequence(S sequence)

此外,向量不仅需要一个模板参数,而是两个(参见 StoryTeller 答案(

它类似于这个问题:https://stackoverflow.com/a/29493191/1889040

这是因为矢量是<type, allocator>的模板

代码应该是

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
void show_element(T ob)
{
cout << ob << " ";
}
template<template<class,class> class S, class T, class Allocator>
void show_sequence(S<T, Allocator> sequence)
{
for_each(sequence.begin(), sequence.end(), show_element<T>);
}
int main(int argc, char const *argv[])
{
std::vector<int> v(20, 0);
//here problem solved
show_sequence<vector, int, allocator<int> > (v);
show_sequence(v);
return 0;
}

最新更新