简体   繁体   中英

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.

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);
}

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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