簡體   English   中英

為什么std :: function不能接受推導類型作為模板參數?

[英]Why can std::function not accept a deduced type as its template parameter?

#include <functional>

using namespace std;

template<class CharType>
void f1(CharType* str, function<bool(CharType)> fn_filter)
{}

template<class CharType>
void f2(CharType* str, function<bool(char)> fn_filter)
{}

void f3(char* str, char c)
{
    auto fn_filter = [=](char e) -> bool 
    {
        return e == c; 
    };

    f1(str, fn_filter); // error C2784
    f2(str, fn_filter); // OK
}

int main()
{
    f3("ok", 'k');
}

// error C2784: 'void f1(CharType *,std::function<bool(CharType)>)' 
// : could not deduce template argument for 'std::function<bool(CharType)>' 
// from 'f2::<lambda_36be5ecc63077ff97cf3d16d1d5001cb>'

我的編譯器是VC ++ 2013。

為什么f1不能按預期工作?

lambda沒有類型std::function<bool(char)> ,它只是一些具有實現定義類型的可調用對象。

它可以轉換std::function<bool(char)> ,但這無助於編譯器推導出模板案例的類型。 例如,可以為CharType提供很多可能性,lambda可以將其轉換為std::function<bool(CharType)>

編譯器嘗試將lambda的類型與模板函數的參數進行匹配。 lambda例如具有類似lambda_t_1234的類型,模板參數是std::function<bool(CharType)> 這些類型是不相關的,並且不清楚CharType應該在這里。

這對lambdas或std::function<>也沒有特殊之處。 所有這些情況都會發生同樣的情況:

template<typename Char>
void f(const std::basic_string<Char> &str) {
}

如果您嘗試使用char*參數調用此模板函數,則它將無法工作,因為與模板參數的連接不明確。

編譯器的問題是決定使用哪個參數進行類型推導。 如果你通過從第二個參數中斷可能的推論並強制它使用第一個參數來幫助編譯,它會按預期工作:

template<typename T> struct identity { using type = T; };

template<class CharType>
void f1(CharType* str, typename identity<function<bool(CharType)>>::type fn_filter)
{}

實例

暫無
暫無

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

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