簡體   English   中英

如何將模板 function 作為 C++ 中的參數傳遞?

[英]How to pass a template function as an argument in C++?

考慮一下:

template <class T_arr, class T_func>
void iter(T_arr *arr, int len, T_func func)
{
    for(int i = 0; i < len; i++)
    {
        func(arr[i]);
    }
}

void display(int a) {
    std::cout << "Hello, your number is: " << a << std::endl;
}

int main(void)
{    
    int arr[] = {1, 2, 3};

    iter(arr, 3, display);
    return (0);
}

但是,如果我嘗試將顯示 function 更改為模板,則可以按預期工作:

template <class T>
void display(T a) {
    std::cout << "Hello, your number is: " << a << std::endl;
}

它停止工作,我收到此錯誤:候選模板被忽略:無法推斷模板參數“T_func”。

如何理解這一點?

您需要顯式指定用於display的模板參數:

iter(arr, 3, display<int>);

或者使iter器采用 function 指針:

template <class T_arr>
void iter(T_arr *arr, int len, void (*func)(T_arr))
{
    for(int i = 0; i < len; i++)
    {
        func(arr[i]);
    }
}

那么你也能

iter(arr, 3, display); // template argument gets deduced as int

暫無
暫無

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

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