Reputation: 31
I would like to write a function in C++ that takes a matrix as an optional argument. If the user ends up passing the matrix when calling the function, it will be modified by the function, so I'm implementing a pass by reference.
According to the accepted answer for this previous question, this can be done by making the default value an empty Mat, such as:
void foo(..., cv::Mat &matrix = cv::Mat()) {
// code
return;
}
However, when I try to compile this in OpenCV 3.2, I get the «invalid initialization of non-const reference of type ‘cv::Mat&’ from an rvalue of type ‘cv::Mat’» error.
Has this feature changed since OpenCV 2.4, or could the issue be somewhere else?
Upvotes: 3
Views: 2573
Reputation: 41
This is because C++ does not allow you to initialize a non-const reference with an rvalue.
So you can either:
1) make the reference const -- wouldn't suit you since you want to change the content of matrix in the function
or
2) have a cv::Mat
init variable stored globally in your module:
static const cv::Mat g_mat = cv::Mat();
void foo(..., cv::Mat &matrix = g_mat) {
Upvotes: 4
Reputation: 110
I might be wrong because I'm a beginner in those matters but here's what I think.
You want to pass by ref an optional argument. The issue is that a reference with the symbol & is a reference to an l-value, which is an object that exists. C++ does not allow what you have written because matrix
is an r-value, that is a temporary object that has not an actual memory address associated to it.
The only way you can pass cv::Mat &matrix = cv::Mat()
is by const-ing it,const cv::Mat &matrix = cv::Mat()
which of course is not what you need.
The simplest solution IMHO is to just overload your function definition so that you have
void foo(...args);
void foo(...args, cv::Mat &matrix);
Hope it helps
Upvotes: 8