如何获得模板参数包来推断按引用而不是按值传递?

编程入门 行业动态 更新时间:2024-10-27 12:33:47
本文介绍了如何获得模板参数包来推断按引用而不是按值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的类中, wrapper 获取一个指向任意 const 方法的指针,并返回调用结果删除 const 的方法。这可以用来生成相应的非 const 方法...

In the following class, wrapper takes a pointer to an arbitrary const method and returns the result of a call to that method with const removed. This can be used to generate the corresponding non-const method...

struct C { int x[10]; int const& get(int i) const { return x[i]; } int const& getr(int const& i) const { return x[i]; } template<typename T, typename... Ts> auto& wrapper(T const& (C::*f)(Ts...) const, Ts... args) { return const_cast<T&>((this->*f)(args...)); } int& get(int i) { return wrapper(&C::get, i); } int& getr(int const& i) { return wrapper(&C::getr, i); } };

几乎。

问题是最终方法 getr()无法编译,因为传递给 wrapper()的参数列表并不意味着传递-引用。等到进入 wrapper()时,编译器正在寻找 getr()。

The problem is that the final method getr() cannot be compiled, because the argument list passed to wrapper() doesn't imply pass-by-reference. By the time we get inside wrapper() the compiler is looking for a pass-by-value version of getr().

这有招吗?

推荐答案

您可以完美转发该函数的参数:

template<typename T, typename... Ts, typename... Args> auto& wrapper(T const& (C::*f)(Ts...) const, Args&&... args) { return const_cast<T&>((this->*f)(std::forward<Args>(args)...)); }

这是通过使 args 转发参考参数包。请注意,我们需要引入一个新的 Args 模板参数包,以便正确推断出参数。

This is achieved by making args a forwarding reference parameter pack. Note that we need to introduce a new Args template parameter pack in order to deduce the arguments correctly.

更多推荐

如何获得模板参数包来推断按引用而不是按值传递?

本文发布于:2023-11-08 13:22:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:推断   如何获得   而不是   模板   参数

发布评论

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

>www.elefans.com

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