[英]C++(11) Default arguments for functions as template parameters, or as function pointers
基本上,我希望可以使用默認參數來調用函數指針。 看一下以下內容:
#include <iostream>
using namespace std;
int function(int arg1 = 23)
{
printf("function called, arg1: %d\n", arg1);
return arg1 * 3;
}
template<typename Fn> int func(Fn f)
{
int v = 3;
f(); //error here 'error: too few arguments to function'
f(23); //this compiles just fine
return v;
}
int main() {
func(&function);
printf("test\n");
return 0;
}
是否可以通過某種方式(欺騙性或其他方式)從函數指針(或模板參數)中調用帶有默認參數的函數,而無需明確指定該參數?
是的,有一個好方法。 功能對象。 我強烈建議您查看此鏈接。
http://www.stanford.edu/class/cs106l/course-reader/Ch13_Functors.pdf
與std::bind
。 它返回一個函數對象,該對象使用您傳遞給綁定表達式的參數調用該函數:
auto f = std::bind(&function, 23);
func(f);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.