Let's consider a class with overloaded unary operator & (Address-of). Let it be class A
template <class C>
class A
{
public:
C * operator &()
{
return &data;
}
//...
private:
C data;
}
Now I want to pass to some function a pointer of type A
to fill its data
. Let us call it f
void f(A * auto_containter)
{
//...
}
But it is clear why the code bellow wouldn't work (even wouldn't compile). It is because the overloaded operator is called.
A a;
f(&a);
The question is following:
Is there any syntax to pass address of a
to f
? If no, then for me it is very strange why it is allowed to overload unary operator &
, because it makes code more buggy and difficult to understand. Or there are some other reasons?
You overload a unary operator with either a nonstatic member function that has no parameters, or a nonmember function that has one parameter. Suppose a unary operator @ is called with the statement @t , where t is an object of type T .
Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++) decrement(- -)
In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set.
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
Is there any syntax to pass address of
a
tof
?
Yes, there's ugly syntax:
f( reinterpret_cast<A*>( &reinterpret_cast<char&>(a) ) );
boost::addressof
is a nice and generic wrapper around it.
Use std::addressof
function(or boost::addressof
pre C++11). In any case, overloading unary & is highly dubious. Why do it instead of having a named function that returns the address of your data?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With