如何将模板函数作为模板函数的参数传递?

问题描述 投票:-1回答:1

我想将模板函数作为模板函数的参数传递。在以下代码的“ meta_func_ok”函数中,已成功将函数指针作为模板函数的参数传递。但是作为模板,编号

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:在函数‘int main()’中:ng.cpp:18:31:错误:无匹配项调用“ 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,Nx){^ ~~~~~~~~~~~ ng.cpp:7:1:注意:模板参数推论/替代失败:ng.cpp:18:31:注意:无法推论模板参数“ F” meta_func_ng(target_func,1);

我该怎么办?预先感谢!

c++ templates
1个回答
1
投票

编译器对类型推断的支持不完善。在第二种情况(meta_func_ng)中,从参数N推断出1类型,但是无法从F推断出target_func类型,因为您没有为target_func的[ C0]类型参数(编译器不足以知道Nmeta_func_ngNtarget_func相同)。

这很好,但是:

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; }

© www.soinside.com 2019 - 2024. All rights reserved.