本文介紹了C++ 重載函數(shù)作為模板參數(shù)的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送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;
}
有沒有辦法告訴編譯器我想傳遞的參數(shù)是第一個‘foo’?
Is there a way to tell the compiler what I want to pass as argument is the first `foo'?
推薦答案
你可以給出一個明確的模板參數(shù):
You can give an explicit template argument:
bar<int(int)>(3, foo);
或?qū)⒛@鈨煽傻暮瘮?shù)名稱強(qiáng)制轉(zhuǎn)換為可以從中推導(dǎo)出模板參數(shù)的類型:
or cast the ambiguous function name to a type from which the template argument can be deduced:
bar(3, static_cast<int(*)(int)>(foo));
或?qū)⑵浒b在另一個函數(shù)(或函數(shù)對象)中以消除歧義
or wrap it in another function (or function object) to remove the ambiguity
bar(3, [](int x){return foo(x);});
這篇關(guān)于C++ 重載函數(shù)作為模板參數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!