How to pass an iterable as a function parameter?

Hello, I have a 'join'-function that joins an array's elements to a string. This is what I want:

1
2
3
4
5
6
7
8
vector<int> a = {1,2,3}
array<int, 3> b = {1,2,3}

cout << join(a) << endl;
// "1, 2, 3"

cout << join(b) << endl;
// "1, 2, 3" 


So I'm trying to declare the function this way:
1
2
3
4
template <typename T, typename C>
string join(const C<const T> &arr, const string &delimiter = ", "){
...
}


But without any success. I understand, that I could declare it this way:
1
2
3
4
template <typename T>
string join(T &arr){
...
}


or this way:
1
2
3
4
template <typename Iter>
string join(Iter &begin, Iter &end){
...
}


But I just wonder, is it possible to implement it like:
1
2
3
4
template <typename T, typename Collection>
string join(const Collection<const T> &data){
...
}


Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <array>
using namespace std;

template <typename Collection>
string join(const Collection &data)
{
   stringstream ss;
   bool first = true;

   for ( auto e : data )
   {
      if ( !first ) ss << ", ";
      first = false;
      ss << e;
   }
   return ss.str();
}


int main()
{
   vector<int> A = { 1, 2, 3, 4 };
   list<double> B = { 5.5, 6.6, 7.7, 8.8 };
   set<int> C = { 100, 99, 98, 97 };
   vector<string> D = { "alpha", "beta", "gamma", "delta" };
   array<int, 3> E = { 1, 2, 3 };


   cout << join( A ) << '\n';
   cout << join( B ) << '\n';
   cout << join( C ) << '\n';
   cout << join( D ) << '\n';
   cout << join( E ) << '\n';
}

1, 2, 3, 4
5.5, 6.6, 7.7, 8.8
97, 98, 99, 100
alpha, beta, gamma, delta
1, 2, 3

Last edited on
Topic archived. No new replies allowed.