Re: using reinterpret_cast to convert between pair<int,int>* and pair<const int, int>*
On Jun 18, 3:30 pm, Jeroen <jeroenwiel...@googlemail.com> wrote:
I have a number of objects of type std::pair<int,int> and would like
to pass a pointer to one of them to a function that is allowed to
write to the second member only.
(Why are you passing a pointer? I am asking because it's suspect in C+
+ code, more often that not. If you pass a pointer to a C++ function
from C++ code, you are expected to handle NULL in the callee. If you
aren't doing that, you should be using a reference).
That said, casting won't get you there, I don't think. So how about
changing the function signature to accept your_pair.first by value or
const reference, and passing another by reference?
If you don't like that, how about passing a proxy object to the
function that can do what you need? e.g.
template<typename first, typename second>
class can_only_modify_second
{
private:
std::pair<first, second>& data_;
public:
can_only_modify_second(std::pair<first, second>& data) : data_(data)
{}
std::pair<first, second>& get_data() { return data_; };
void modify_second(const second& value) { data_.second = value; }
};
then change your function to work with can_only_modify_second in lieu
of pair<>.
By the way, in OOP theory/evangelism/best practices/pick your
buzzword, certain Robert C. Martin abstracted above as "interface
segregation principle". Effectively, he says: between pieces of code,
try using client-specific interfaces. Seems to do it for you (at least
from what you have described so far).
Goran.
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]