[英]How to pass template function as argument of template function?
我想通過模板 function 作為模板 function 的參數。 在下面代碼的 'meta_func_ok' function 中,成功傳遞了 function 指針作為模板 function 的參數。 但作為模板,不。
template < typename N > N
meta_func_ok( N( *f )( N ), N x ) {
return f( x );
}
template < typename F, typename N > N
meta_func_ng( F f, N x ) {
return f( x );
}
template < typename N > N
target_func( N x ) {
return x;
}
int main() {
meta_func_ok( target_func, 1 );
meta_func_ng( target_func, 1 ); // LINE 18
return 0;
}
編譯此代碼會產生以下錯誤。
ng.cpp:在 function 'int main()' 中:ng.cpp:18:31:錯誤:沒有匹配的 function 用於調用 'meta_func_ng(, int)' meta_func_ng(target_func, 1) ^ ng.cpp:7:1: 注意: 候選: 模板 N meta_func_ng(F, N) meta_func_ng( F f, N x ) { ^~~~~~~~~~~~~ ng.cpp:7:1:注意:模板參數推導/替換失敗:ng.cpp:18:31:注意:無法推導模板參數'F' meta_func_ng(target_func, 1);
我能怎么做? 提前致謝!
編譯器對類型推斷的支持並不完善。 在第二種情況下( meta_func_ng
) N
類型是從參數1
推斷出來的,但F
不能從target_func
推斷出來,因為您沒有為target_func
的N
類型參數指定顯式類型(編譯器不夠聰明知道meta_func_ng
的N
與target_func
s N
相同)。
但是,這很好用:
(same code as above here)
int main() {
meta_func_ok( target_func, 1 );
meta_func_ng( target_func<int>, 1 ); // LINE 18
return 0;
}
請參閱此 QA: 編譯器何時可以推斷模板參數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.