【问题标题】:How to pass template function as argument of template function?如何将模板函数作为模板函数的参数传递?
【发布时间】:2019-09-28 01:36:34
【问题描述】:

我想传递模板函数作为模板函数的参数。在下面代码的“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, N x ) { ^~~~~~~~~~~~~ ng.cpp:7:1: 注意:模板参数 演绎/代入失败:ng.cpp:18:31:注意:无法演绎 模板参数‘F’ meta_func_ng(target_func, 1 );

我该怎么办?提前致谢!

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    编译器对类型推断的支持不完善。在第二种情况下 (meta_func_ng),N 类型是从参数 1 推断出来的,但是 F 不能从 target_func 推断出来,因为您没有为 target_func 的 @ 指定显式类型987654328@ 类型参数(编译器不够聪明,无法知道meta_func_ngNtarget_funcs 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;
    }
    

    查看此质量检查:When a compiler can infer a template parameter?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 2012-12-27
      • 2017-06-14
      • 2010-11-13
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多