Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Function template specialization for array

I tried to write a function to do whatever to 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 was designed to operate STL containers and it's OK. But I want another version for 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 "Partial template specialization for arrays"(and several another related post), but it's for class template. And I also know that when you're specializing a function template, you are actually overloading it. Anyway, the solution in that post can't be implemented here.

Any (or maybe no) way could I do this? :-) Thx for tolerating my poor English and thx for your helps.

like image 929
sqd Avatar asked Dec 26 '22 03:12

sqd


2 Answers

You could pass it by reference :

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

But the true solution to your problem is to pass a pair of iterators to a single function template (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));
}
like image 23
quantdev Avatar answered Dec 28 '22 22:12

quantdev


You miss the reference to array:

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

BTW, in your case, you may simply use (const) reference in the generic case:

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);
}
like image 78
Jarod42 Avatar answered Dec 29 '22 00:12

Jarod42