如何获得模板参数包来推断按引用而不是按值传递? [英] How do I get a template parameter pack to infer pass-by-reference rather than pass-by-value?

查看:80
本文介绍了如何获得模板参数包来推断按引用而不是按值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的类中, 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.

这篇关于如何获得模板参数包来推断按引用而不是按值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆