簡體   English   中英

將 lamda 與模板函數一起使用時出現錯誤 C2672 和 C2784

[英]error C2672 and C2784 when using lamdas with template functions

我已經編寫了以下 function,它在遍歷 2d 向量時隱藏了循環:

    template<typename ElementType>
    void iterateOver2DVector(std::vector<std::vector<ElementType>> & vec, 
                             std::function<void(ElementType & element)> function)
    {
        for(auto & row : vec)
        {
            for(auto & element : row)
            {
                function(element);
            }
        }
    }

但我得到錯誤:

'function': no matching overloaded function found

'declaration' : could not deduce template argument for 'type' from 'type'

像這樣與 lambda 一起使用時:

iterateOver2DVector(graph, [](Node & node) { node.update(); } );

有人知道我做錯了什么嗎?

該調用將嘗試從第一個和第二個參數/參數對中推斷出ElementType

第二對將失敗,因為 function 的第二個參數不是std::function ,而是閉包類型。

如果一對失敗,則整個推導失敗,即使另一對會正確推導ElementType的模板參數。

您的 function 不需要從第二個參數/參數對中推導出ElementType ,因此您可以將其設為non-deduced context ,這樣就不會嘗試推導它。

一種常見的方法是使用std::type_identity_t

template<typename ElementType>
void iterateOver2DVector(std::vector<std::vector<ElementType>> & vec, 
                         std::type_identity_t<std::function<void(ElementType & element)>> function)

std::type_identity_t<T>std::type_identity<T>::type的別名,它是T的別名,但是由於類型T現在是 a ::的左側,它處於非推導上下文中。

std::type_identity_t僅在 C++20 之后可用,但它可以在 C++ 的早期版本中輕松定義:

template<typename T> struct type_identity { using type = T; };
template<typename T> using type_identity_t = typename type_identity<T>::type;

然而,在這種情況下, std::function只是不必要的開銷。 直接接受閉包類型,而不是std::function

template<typename ElementType, typename F>
void iterateOver2DVector(std::vector<std::vector<ElementType>> & vec, 
                         F function)

std::function僅在您打算存儲可調用對象而不依賴其特定類型時才有用,例如在 class 成員中,即使在這種情況下,也可以在分配給成員時轉換為std::function

暫無
暫無

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

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