0

I have a function that has a similar behavior of this:

void process(const T& input,T& output){
    if(&input==&output){
        //Alter output directly
    }
    else{
        output=input; //Deep Copy
        //Alter output
    }
}

Use case 1:

T i;
//fill i
T o;
process(i,o);

Use case 2:

T io;
//fill io
process(io,io);

I want to change this function deceleration to be more readable:

T process(const T& input){
   //What to do here?
}

Use case 1:

T i;
//fill i
auto o = process(i);

Use case 2:

T io;
//fill io
io=process(io);

Question: How can I imitate the previous methodology of dealing with in-place cases? How should I implement it? I need to avoid deep copying when it is the same object.

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • 1
    Why not have two functions? The function is not aware of where you store the result. – Benoit Apr 19 '16 at 07:33
  • What should `auto o = process(i)` do if it does not make a deep copy? `o` should be a reference to `i`? – Holt Apr 19 '16 at 07:34
  • @Holt it must do deep copy. &i != &o – Humam Helfawi Apr 19 '16 at 07:36
  • @Benoit Sorry but did not get you – Humam Helfawi Apr 19 '16 at 07:36
  • @Holt mmmm no it is not.. One should fill 'i' then call the 'process' function to get 'o' output – Humam Helfawi Apr 19 '16 at 07:39
  • @HumamHelfawi, you want two use cases that do unrelated things. Therefore I think you need two functions called for instance `process_in_place` and `process_copy` – Benoit Apr 19 '16 at 07:46
  • @Benoit.. I see. However, it was possible when the output was a reference variable. So, I thought there may be some solution with output as return value. Thanks – Humam Helfawi Apr 19 '16 at 07:47
  • 1
    return `void` and just use `process(o)` in both cases. Start with `o = i;` if requred – M.M Apr 19 '16 at 07:55
  • @M.M You mean I should provide just in-place version of the function the it is the user responsibility to make a copy if needed. It solves the problem but still not so readable IMO. Thanks – Humam Helfawi Apr 19 '16 at 08:07

0 Answers0