在下面的类中, 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.
更多推荐
如何获得模板参数包来推断按引用而不是按值传递?
发布评论