[英]How do I get a template parameter pack to infer pass-by-reference rather than pass-by-value?
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. 在下面的类中,
wrapper
使用指向任意const
方法的指针,并在删除const
返回对该方法的调用结果。 This can be used to generate the corresponding non- const
method... 这可以用来生成相应的非
const
方法...
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); }
};
almost. 几乎。
The problem is that the final method getr()
cannot be compiled, because the argument list passed to wrapper()
doesn't imply pass-by-reference. 问题在于最终方法
getr()
无法编译,因为传递给wrapper()
的参数列表并不意味着传递引用。 By the time we get inside wrapper()
the compiler is looking for a pass-by-value version of getr()
. 等到进入
wrapper()
,编译器正在寻找getr()
的按值传递版本。
Is there a trick to this? 有这个窍门吗?
You can perfect forward the arguments to the function: 您可以将参数完美地转发到该函数:
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)...));
}
This is achieved by making args
a forwarding reference parameter pack. 这是通过使
args
成为转发参考参数包来实现的。 Note that we need to introduce a new Args
template parameter pack in order to deduce the arguments correctly. 注意,我们需要引入一个新的
Args
模板参数包,以便正确推断出参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.