繁体   English   中英

STL容器作为函数中的模板参数,调用错误

[英]STL container as template parameter in function, error in call

不能理解什么是代码,第二个函数定义或主要调用此函数? 我认为(但不确定)调用中的问题,导致未调用代码的编译良好。 编译器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)

此外,vector不仅采用一个模板参数,还采用两个参数(请参见StoryTeller答案)

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

因为vector是<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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM