language: C++ 4.7.2 (gcc-4.7.2)
date: 693 days 20 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <typeinfo>
 
template<class T>
struct addr_impl_ref
{
  T & v_;
 
  inline addr_impl_ref( T & v ): v_( v ) {}
  inline operator T& () const { return v_; }
 
private:
  addr_impl_ref & operator=(const addr_impl_ref &);
};
 
template<class T>
struct addressof_impl
{
  static inline T * f( T & v, long ) {
    std::cout << "reference - " << typeid(T).name() << " - ";
    return reinterpret_cast<T*>(
        &const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
  }
 
  static inline T * f( T * v, int ) {
    std::cout << "pointer - " << typeid(T).name() << " - ";
    return v;
  }
};
 
template<class T>
T * addressof( T & v ) {
  T* t = addressof_impl<T>::f( addr_impl_ref<T>( v ), 0 );
  std::cout << t << "\n";
  return t;
}
 
 
struct pointer {
  int* i;
  operator int*() const { return i; }
  operator int&() const { return *i; }
};
 
void func();
 
typedef void (*func_ptr)();
 
struct convertible_ptr {
  operator func_ptr() { return func; }
};
 
typedef void (&func_ref)();
 
struct convertible_ref {
  operator func_ref() { return func; }
};
 
int main() {
  int i; int* p; int** pp; int a[5];
  addressof(i);
  addressof(p);
  addressof(pp);
  addressof(a);
 
  pointer P;
  addressof(P);
 
  addressof(func);
  //addressof(&func); // does not compile
 
  convertible_ptr cp;
  addressof(cp);
 
  convertible_ref cr;
  addressof(cr);
}