Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.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++ 是否可以将引用传递给可变模板函数?_C++_C++11_Pass By Reference_Variadic Templates - Fatal编程技术网

C++ 是否可以将引用传递给可变模板函数?

C++ 是否可以将引用传递给可变模板函数?,c++,c++11,pass-by-reference,variadic-templates,C++,C++11,Pass By Reference,Variadic Templates,假设我有一个使用CRTP并提供可变模板静态成员函数的基类 template<typename derived_task> struct task_impl : library::task { /* some useful functionality implemented using CRTP */ /// static method for spawning a task. template<typename... Args> static vo

假设我有一个使用CRTP并提供可变模板静态成员函数的基类

template<typename derived_task>
struct task_impl : library::task
{
   /* some useful functionality implemented using CRTP */
   /// static method for spawning a task.
   template<typename... Args>
   static void spawn(Args... args)
   { library::spawn(new task(args...)); }
 };

这里发生的是
spawn()
创建容器的副本,而不是通过引用传递原始容器。有没有办法强制执行引用

您可以使用
std::ref
包装参数


这种情况实际上相当频繁,例如,在使用带有引用参数的函数创建
std::thread
s时,或者在使用
std::bind
时,您有两个选项,或者使用
引用包装
包装参数,以便函数调用复制
引用包装
而不是它引用的对象,或者使变量函数使用完美转发,以便它可以通过引用传递参数:

template<typename... Args>
 static void spawn(Args&&... args)
 { library::spawn(new task(std::forward<Args>(args)...)); }
模板
静态无效生成(Args&&…Args)
{library::spawn(新任务(std::forward(args)…);}

std::ref
应该适用于此,不是吗?确实适用。谢谢PS.将接受单线回答。PPS。10分钟内(不允许提前:-(我并不认为这是个问题,只是很多人似乎忘记了,对于
std::bind
和其他许多东西,默认情况下是按值存储的。@Plasmah指出,经过编辑,我不再认为这是个问题。在看到Jonathan的答案后,我检查了
std::thread
,发现它使用了perf通过
std::forward
进行ct转发。那么,问题出在哪里?@Walter:@Walter,
\u bind\u simple
做什么呢?它使用
std::decay
并按值复制参数。完美转发用于在按值复制之前避免不必要的复制,但这些复制是标准所要求的。性能当然,对于已经是引用的对象,ct转发比使用
std::ref
要好得多。事实上,
std::thread
也使用它。我仍在学习可变模板使用的所有技术。感谢您的评论,我将varargs作为右值(或引用):
void spawn(Args…
==>
void spawn(Args&&…
)为什么还要使用完美转发?
container c( /* args for ctor */ );
my_task::spawn(c,0);
template<typename... Args>
 static void spawn(Args&&... args)
 { library::spawn(new task(std::forward<Args>(args)...)); }