dimanche 5 avril 2020

Accepting both lvalue and rvalue references to class template argument

I have the following class:

template<typename T>
class Foo {
   // ...
   void frobnicate(const T& arg) {
       // [lots of code here]
       do_the_thing(arg);
       // [lots of code here]
   }

   void frobnicate(T&& arg) {
       // [lots of code here, same as above]
       do_the_thing(std::move(arg));
       // [lots of code here, same as above]
   }
}

Is there a way to remove the code duplication between the two versions of frobnicate without introducing "post" and "pre" helper functions?

Ideally, I'd like to write something like:

   void frobnicate(/*what goes here?*/ arg) {
       // [lots of code here]
       if (is_rvalue_reference(arg))
          do_the_thing(std::move(arg));
       else
          do_the_thing(arg);
       // [lots of code here]
   }

Is there a way to do this?

I think if T wasn't a class template argument but a function template argument, I could probably use template argument deduction in some clever way (though I'm not sure how exactly I'd do that either), but with the class involved I am not sure where to start...

Aucun commentaire:

Enregistrer un commentaire