Re: error: passing `const ...' as `this' argument of `...' discards
qualifiers
On Aug 12, 9:23 am, Giovanni Gherdovich
<gherdov...@students.math.unifi.it> wrote:
Hello,
I'm doing some toy experiments to see how
the algoritm std::transform and the function
adapter std::bind2nd can play together, but
my compiler give my the error
error: passing `const traslate' as `this' argument of
`circle traslate::operator()(circle, std::vector<double,
std::allocator<double> >)'
discards qualifiers
It should be like I'm trying to modify
something which is declared as const...
The example code follows.
I define the type `circle', which holds
center and radius of a circle, then I
introduce a vector of circles and try to
traslate them all with std::transform.
I need std::bind2nd to fix the traslation
for all the circles.
Note that I'm forced to define the
temporary object `traslate' to meet
std::bind2nd input specifications.
// ========================
================
#include <vector>
#include<functional>
#include<algorithm>
using namespace std;
struct circle
{
vector<double> center;
How about std::pair instead? Or, perhaps even better, make your own
point class with members x and y. std::vector is overkill here.
double radius;
};
struct traslate
{
typedef circle first_argument_type;
typedef vector<double> second_argument_type;
typedef circle result_type;
Consider inheriting from std::binary_function instead of this.
circle operator()(const circle original, const vector<double>
traslation)
You probably want to use references for both of these parameters to
prevent unnecessary copies. (They may be inlined away or relatively
trivial here, but maybe not if you call this a lot.) You should also
use std::pair or your own point class here, too, since you only have x
and y coordinates. Since this function doesn't modify the object's
state, it should be made const (note also the references):
circle operator()(
const circle& original,
const vector<double>& traslation) const
{ ... }
However, since your functor has no state, you should just make this a
plain old function rather than a function object.
{
circle traslated = original;
traslated.center[0] += traslation[0];
traslated.center[1] += traslation[1];
return traslated;
}
};
int main()
{
vector<circle> lots_of_circles(10);
vector<circle> some_other_circles(10);
vector<double> traslation(2);
traslation[0] = 123;
traslation[1] = 321;
transform(lots_of_circles.begin(), lots_of_circles.end(),
some_other_circles.begin(), bind2nd(traslate(), traslation));}
// ========================
================
Can you see the reason of the above mentioned error?
You're creating a temporary object -- the instance of translate --
which is bound to a const reference in bind2nd. The function you are
calling is not const. Add const to the member function, or better,
make it a plain old function.
See these FAQs for more info on const-correctness:
http://www.parashift.com/c++-faq-lite/const-correctness.html
Cheers! --M