C ++: specializing function templates for an array

I tried to write a function to do anything from a series of data.

//For stl containers
template<typename T>
void foo(T x){
    for(auto iter=x.begin();iter!=x.end();++iter)
        do_something(*iter);
}

      

This function is designed to work with STL containers, and that's okay. But I want a different version for the C array. So I tried this:

//For C-array
template<typename T,size_t N>
void foo(T x[N]){
    //blabla
}
//Error

      

I've read Specializing Partial Template for Arrays (and a few other related posts), but this is for a class template. And I also know that when you specialize in a function template, you are actually overloading it. Anyway, the solution in this post cannot be implemented here.

Any (or maybe not) way I could do this? :-) thanks for your tolerance of my poor english and thanks for your help.

+3


source to share


2 answers


You will miss the reference to the array:

template<typename T, size_t N>
void foo(T (&x)[N]){
    //blabla
}

      

By the way, in your case, you can just use link ( const

) in general:



template<typename T>
void foo(T& x){
    using std::begin;
    using std::end;

    for (auto iter = begin(x); iter != end(x); ++iter)
        do_something(*iter);
}

      

or even better:

template<typename T>
void foo(T& x){
    for (auto&& e : x)
        do_something(x);
}

      

+5


source


You can pass it by link:

template<typename T,size_t N>
void foo(T (&x)[N]){
    //blabla
}

      



But the true solution to your problem is to pass a couple of iterators into the single pattern (working for both arrays and standard containers):

template<typename Iterator>
void foo(Iterator begin, Iterator end){
    for(auto it = begin; it!=end; ++it)
        do_something(*it);
}
int main()
{
   int a[] = {1, 2, 3, 4, 5};
   foo(std::begin(a) , std::end(a));

   std::vector<int> v = {1, 2, 3, 4, 5};
   foo(std::begin(v) , std::end(v));
}

      

+5


source







All Articles