The following code compiles and works as expected.
#include <vector>
void function(std::vector<int> vec, int size=1);
int main(){
std::vector<int> vec = {1,2,3};
function(vec);
}
void function(std::vector<int> vec, int size){
//code..
return;
}
However, I would like the size parameter's default value to be deduced based on a previous parameter. So for example:
void function(std::vector<int> vec, int size=vec.size());
But this however results in:
error: local variable ‘vec’ may not appear in this context
Which doesn't surprise me; I assume it needs to know the default value at compile time. So do I make the function templated? How would I make the function templated in such a way that the parameter is still an int, and the vector, is still a vector of ints, and the size parameter is deduced to be the passed in vector's size by default.
I would not like to have to pass in the size of the vector during the function call.
I assume it needs to know the default value at compile time, that is not true, actually you can using global variable as default argument, but because the function parameter evaluation order are not defined, C++ standard explicitly prohibit access parameter when evaluate default value.