I have an issue with the use of aliases in function arguments. Here is my problem.
Let’s consider this function definition
void thisIsSparta(int& number){
...
}
at call time, it works perfectly well with the following code :
int king = 1;
thisIsSparta(king);
but I have a mismatch error when I try this :
thisIsSparta(1);
I can easily guess that the error occurs because there is simply no variable to alias, hence the error. However, I don’t want the programmer to worry about using only one of the two approaches, this second function call should work as fine !
The only solution I see is to create another function with no alias argument, in addition to the first one :
void thisIsSparta(int number){
}
But this would result in an awful code duplication, and I’m not a huge fan of this.
Furthermore, the program could decide to use this second definition instead of the former when I use a variable. I then loose the interest of the alias, whose purpose is to avoid variable copy.
Does anyone have a solution to my problem ? Indeed, this is a simplified example, in practice I have a generic type in argument for this function, and it could be arbitrarily big. This is why I’d like to use an alias to avoid copy.
For basic types, just pass by value. It’s faster than passing a reference, so ditch the passing by reference and just have
For large types, you can only bind temporaries to
constreferences, so you can declare the method asIf you’re modifying the value inside the function, then passing a temporary as argument doesn’t make sense, so the compiler is right to complain, but in case you don’t, use the above two options.