Question

I am trying to interface a C library to my C++ project. The library has its own vector type, assume to be VECTOR, and it provides element access:

int vector_set_value(VECTOR* vec, int index, double new_value);
int vector_get_value(VECTOR* vec, int index, double* retrieved_value);

Now it would be good to wrap the get and set operations by operator[] overloading

double& operator[](int index);
const double& operator[](int index) const;

But how do I tell operator[] have different behavior, between vec[index]=3 and double value=vec[3]? For the prior vector_set_value should be called while for the latter vector_get_value should be called.

Was it helpful?

Solution

I would not attempt to wrap one interface into the other.

That being said, if you really want to do this one possible solution is to create a proxy object, and have your operator[] return that proxy object. The proxy object would have conversions into the underlying type const double& for reading, and overloaded operator= for writing. Each one of them would call the appropriate library function.

This will allow for syntax that looks like that of C++ std::vector: MyVector v(...); v[1] = 10.1; double d = v[1]; but it will be problematic. The proxy object cannot replace the real type in all contexts, only in some of them. And even there, the semantics are different, so while it may look like a regular vector, one day you will try to use the proxy in a way it does not support and you will be puzzled at the leaking abstraction

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top