Home > Back-end >  Create a copy on demand
Create a copy on demand

Time:02-19

Is there an idiomatic way to invoke the creation of a copy in an expression?

For example say I have a function declared as:

template <class T>
void foo(T&& arg)
{
}

Now I need to call foo with a copy of my object:

MyType object;
foo(object);

As written above, I will have a call on void foo(MyType& arg), but I don't want to pass a reference to my object. I also want to avoid moving from my object in order to trigger deduction of void foo(MyType&& arg).

What I want to do is create a copy of object at the call site of foo:

foo(copy(object));

I have tried the following things:

  • Creating a copy function myself, to generate objects: template <class T> T copy(T arg) { return arg; }
  • Copy by means of forward casting: foo(std::forward<MyObject>(object)), but don't think it works in generic code
  • Explicitly copying by creating a local variable to pass to foo: MyType copy(object); foo(std::move(copy));

Is there a standard library facility or a "generally accepted" way to do this?


EDIT:

As mentioned in the comments, foo(MyType(object)) is always a solution. I'm asking whether there is an idiomatic way because in general spelling out the type in this case can be less safe:

// Converting constructors may create spurious problems:
foo(AnotherType(object)); 
// This can compile even if decltype(object) != AnotherType

whereas a solution that requires no attention in specifying the type is always safe:

foo(copy(object)); 

CodePudding user response:

You can build a decay-copy function yourself:

template <class T> 
constexpr std::decay_t<T> decay_copy(T&& v)
{ return std::forward<T>(v); }

then

foo(decay_copy(object)); 

It's worth noting that you can also use auto(x) to get language-supported decay-copy in C 23:

foo(auto(object)); 

Demo

See P0849 for more details on auto(x).

  • Related