Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL container as template parameter in function, error in call

Cant understand what is wrogn with code, second function definition or call of this function in main? I think, but not sure, problem in call, cause without calling code compiles well. Compiler 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;
}
like image 408
Anton Avatar asked Dec 10 '25 17:12

Anton


2 Answers

std::vector isn't a template of one parameter, it takes an allocator type as well. You can use it as vector<T> simply because the second parameter has a default (std::allocator<T>).

As it's written, your template function cannot accept any standard container, since off the top of my head, none take just a single type parameter.

An approach that would work, and not require you to know how many template parameters a container requires, is to accept a container type (not template), and glean the value type from the container type.

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

All standard containers have a value_type member, so this will work with any of them. Furthermore, it will work with any container that takes its cue from the standard library.

like image 55
StoryTeller - Unslander Monica Avatar answered Dec 13 '25 05:12

StoryTeller - Unslander Monica


The problem is that std::vector is a template but std::vector<int> is a type.

When you are giving the second one to the function, you are giving one type and not a template.

So, you can rewrite your function as :

template<class S>
void show_sequence(S sequence)

Moreover, vector does not take only one template paramete but two (see StoryTeller answer)

like image 28
Antoine Morrier Avatar answered Dec 13 '25 07:12

Antoine Morrier