本文介紹了C++ 重載函數作為模板參數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我的代碼的簡化版本在這里
the simplified version of my code is here
int foo(int x)
{
return x;
}
int foo(int x, int y)
{
return x+y;
}
template<typename unary_func>
int bar(int k, unary_func f)
{
return f(k);
}
int main()
{
bar(3, foo);
return 0;
}
有沒有辦法告訴編譯器我想傳遞的參數是第一個‘foo’?
Is there a way to tell the compiler what I want to pass as argument is the first `foo'?
推薦答案
你可以給出一個明確的模板參數:
You can give an explicit template argument:
bar<int(int)>(3, foo);
或將模棱兩可的函數名稱強制轉換為可以從中推導出模板參數的類型:
or cast the ambiguous function name to a type from which the template argument can be deduced:
bar(3, static_cast<int(*)(int)>(foo));
或將其包裝在另一個函數(或函數對象)中以消除歧義
or wrap it in another function (or function object) to remove the ambiguity
bar(3, [](int x){return foo(x);});
這篇關于C++ 重載函數作為模板參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!