簡體   English   中英

C ++:數組的函數模板特化

[英]C++: Function template specialization for array

我試着編寫一個函數來對一系列數據做任何事情。

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

這個功能是為了操作STL容器而設計的,沒關系。 但我想要另一個版本的C陣列。 所以我嘗試了這個:

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

我讀過“陣列的部分模板專業化” (以及其他幾個相關的帖子),但它是用於類模板的。 而且我也知道,當你專注於一個功能模板時,你實際上正在超載它。 無論如何,該帖子中的解決方案無法在此實施。

我可以做任何(或者沒有)方式嗎? :-)感謝你容忍我糟糕的英語和thx以獲得幫助。

你錯過了對數組的引用:

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

順便說一下,在你的情況下,你可以簡單地在通用情況下使用( const )引用:

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

甚至更好:

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

你可以通過引用傳遞它:

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

但是問題的真正解決方案是將一對迭代器傳遞給單個函數模板(適用於數組和標准容器):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM