简体   繁体   中英

Is it possible to pass a reference to a variadic template function?

Suppose, I have a base class using CRTP and providing a variadic template static member function

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...)); }
 };

and the derived class

struct my_task : task_impl<my_task>
{
  /* implementation using functionality of task_impl<> */
  my_task(container&c, int i);
};

and then want to use the variadic template member via

container c( /* args for ctor */ );
my_task::spawn(c,0);

What happens here is that spawn() creates a copy of container rather than passing the original container by reference. Is there any way to enforce a reference?

You have two options, either wrap the argument with a reference_wrapper so the function call copies the reference_wrapper not the object it referes to, or make your variadic function use perfect forwarding so that it can pass arguments by reference:

template<typename... Args>
 static void spawn(Args&&... args)
 { library::spawn(new task(std::forward<Args>(args)...)); }

You can use std::ref to wrap the parameters.

This actually occurs rather frequently, for example when creating std::thread s with functions that take reference parameters, or when using std::bind .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM