模板参数类型推演在函数对象中不起作用(Template argument type deduction won't work within a function object)

编程入门 行业动态 更新时间:2024-10-27 16:37:09
模板参数类型推演在函数对象中不起作用(Template argument type deduction won't work within a function object)

我有一个模板函数,带有模板化参数类型的另一个函数。

使用它时,我必须明确指定参数类型(1)否则不会编译(2)。

template<typename T> void process(const std::function<void(const T &)>& f) { // ... } process<Foo>( [&](const Foo& arg){/*...*/} ); // (1) Ok! // process( [&](const Foo& arg){/*...*/} ); // (2) Won't Work!

让(2)工作有什么诀窍吗?

I have a template function taking another function with templated argument type.

When using it I have to specify the argument type explicitly (1) otherwise it won't compile (2).

template<typename T> void process(const std::function<void(const T &)>& f) { // ... } process<Foo>( [&](const Foo& arg){/*...*/} ); // (1) Ok! // process( [&](const Foo& arg){/*...*/} ); // (2) Won't Work!

Is there any trick to let (2) work?

最满意答案

让编译器找出整个函数的确切类型:

template<typename T> void process(T&& f) { // ... }

现在你的两个函数调用都可以。

Just let the compiler figure out the exact type of the whole function :

template<typename T> void process(T&& f) { // ... }

Now both your function calls will work.

更多推荐

本文发布于:2023-04-28 01:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   函数   对象   模板   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!