I have a class Object
that I'd like to use as if it were an int
. In other words I want to pass this object to functions that accepts int
, int*
or int&
so that the functions "see" actually ony the wrapped int
value.
The code below illustrates what I want to do. I was able to write the code for int
and int*
but I'm not able to write the code for int&
.
#include <cassert>
class Object
{
public:
int bla = 0;
int val = 0; // the int being wrapped
Object(int v) : val(v) {};
operator int() const { return val; };
int *operator &() { return &val; };
#if 1
int & operator() { return val; }; // << does not compile
#endif
};
int func(int val) {
return val * 2;
}
void Bar(int* pval, int val) {
*pval = val;
}
void Foo(int & pval, int val) {
pval = val;
}
int main() {
int val;
Bar(&val, 123);
assert(val == 123);
Foo(val, 789);
assert(val == 789);
Object o(8);
assert(func(o) == 2 * 8); // operator int()
Bar(&o, 1234); // int *operator &()
assert(o.val == 1234);
#if 1
Foo(o, 456); // << does not compile
assert(o.val == 456);
#endif
}
If #if 1
is replaced with #if 0
, the code works as expected.
Could anybody point me into the right direction so Foo(o, 456);
compiles?
The problem is the conversion operator, which you have the wrong syntax for.
It should be
operator int&() { return val; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.