Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 向成员转发呼叫的模板';s法_C++_Templates_Reference_Sfinae - Fatal编程技术网

C++ 向成员转发呼叫的模板';s法

C++ 向成员转发呼叫的模板';s法,c++,templates,reference,sfinae,C++,Templates,Reference,Sfinae,考虑以下几点: template <typename type> class my_wrapper { type _; template <typename... types, typename std :: enable_if <has_my_method_callable_with_the_following_types <type, types...> :: value> :: type * = nullptr> void my_m

考虑以下几点:

template <typename type> class my_wrapper
{
  type _;

  template <typename... types, typename std :: enable_if <has_my_method_callable_with_the_following_types <type, types...> :: value> :: type * = nullptr> void my_method(types... items)
  {
    _.my_method(items...);
  }
};
显然,上述方法不起作用,因为
x
将通过复制传递给函数,而
my_type::my_method
通过引用接受它。所以我想知道:有没有办法解决这个问题?我当然可以做到:

template <typename... types, typename std :: enable_if <has_my_method_callable_with_the_following_types <type, types & ...> :: value> :: type * = nullptr> void my_method(types & ... items)
{
  _.my_method(items...);
}
template void my_方法(类型和…项)
{
_.my_方法(项目…);
}
但是对称地,当我传递时,比如说,
int
文字时,我会遇到问题,我不能通过引用来获取这些文字,但这对于一些
my_type::my_method(int x)
来说是完全可以接受的

我如何解决这个问题?我想无缝地将所有对
my\u wrapper::my\u method
的调用转发到
type::my\u method

海盗小心:我不能使用继承,所以请不要建议这样做!:)

这正是perfect forwarding和forwarding Reference引入的目的:

template <
  typename... types,
  typename std :: enable_if <has_my_method_callable_with_the_following_types <type, types...> :: value> :: type * = nullptr
> void my_method(types&&... items)
{
  _.my_method(std::forward<types>(items)...);
}
模板<
类型名。。。类型,
typename std::enable_if::type*=nullptr
>void my_方法(类型和项目)
{
_.my_方法(标准::转发(项目)…);
}
工作原理:

语言中有一条特殊的规则,当在
T&
结构中推导
T
时,用于推导的参数是
U
类型的左值,然后
T
被推导为
U&
,而不是
U


净效果是,当参数是转发引用时(
T&&
,对于导出的
T
),它要么是左值引用(如果参数是左值),要么是右值引用(如果参数是右值)
std::forward
然后将其适当地转换回左值或右值。

您正在寻找所谓的“完美转发”调用
.my\u方法(std::forward(items)…
.my\u方法(items…
)@MatteoMonti不要忘记命名的右值引用是左值。如果
my_方法
接受右值引用(或仅按值移动类型),则不带
std::forward
的版本将失败。
template <
  typename... types,
  typename std :: enable_if <has_my_method_callable_with_the_following_types <type, types...> :: value> :: type * = nullptr
> void my_method(types&&... items)
{
  _.my_method(std::forward<types>(items)...);
}