简体   繁体   English

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

[英]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.

相关问题 区分函数模板中的值传递和引用传递 - Distinguish between pass-by-value and pass-by-reference in a function template 函数参数按值传递比按引用传递更快? - Function argument pass-by-value faster than pass-by-reference? 我应该在哪里更喜欢按引用传递或按值传递? - Where should I prefer pass-by-reference or pass-by-value? 区分传递参考和传递价值 - Distinguishing Pass-by-Reference and Pass-by-Value 将按引用传递和按值传递混合到可变参数模板函数是否有效? - Mixing pass-by-reference and pass-by-value to variadic template function valid? C ++中按值传递和按引用传递之间的区别 - Differences between pass-by-value and pass-by-reference in c++ 通过查看装配将值传递与引用传递性能进行比较 - Comparing pass-by-value with pass-by-reference performance by looking at assembly 值传递和 std::move 优于传递引用的优点 - Advantages of pass-by-value and std::move over pass-by-reference 我可以让C ++编译器决定是按值传递还是按引用传递? - Can I let the C++ compiler decide whether to pass-by-value or pass-by-reference? C ++:对于内置(即类似C的)类型,为什么按值传递通常比按引用传递更有效 - C++: Why pass-by-value is generally more efficient than pass-by-reference for built-in (i.e., C-like) types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM