tags:

views:

142

answers:

5

In preparing to a OOP exam, I enjoyed seeing g++ compile the following code (without an instantiation) even though it appeared to make no sense:

template<class T> void f() {
    T t = "a";
    t += 5.6;
    t->b();
    T* p = t;
    p = p*(t/"string");
}

I then set out on a challenge to make this instantiate and compile.

I created the following class:

class A {
    public:
    A(const char* s) {}
    void operator+=(double d) {}
    A operator/(char* str) {return A("");}
    A* operator->() {return this;}
    A* operator=(A& a) {return &a;}
    void b() {}
};
A* operator*(A* a, A b) {return new A("");}

which allowed almost all of the template to work, except the line

T* p = t;

My question is, what operator or constructor will make this line work? Currently it gives me "error: cannot convert ‘A’ to ‘A*’ in initialization"

A: 

My C/C++ is pretty rusty but I really want to say that it's just

T* p = &t;
Pointy
+8  A: 

Use the type conversion operator?

class A {
   //...
public:
    template< class T > 
    operator T*() { return this; }
};

But clearly, it's bad practice.

Klaim
...but it's really bad practice. You want to know wether you are dealing with an object on the stack or with a pointer to an object wherever.
Johannes Rudolph
Yes clearly it's bad practice.
Klaim
Fixed the example to make it work with VS2008, then added that it's bad practice.
Klaim
Works as well.This gives me a lot more conversions than I needed, which is why I didn't mark it as my selected answer.
Tzafrir
+4  A: 

That is a completely meaningless line.

But to make it compilable, you can provide the conversion operator:

operator A* () { return 0; }

Hope you realize how evil this is.

UncleBens
Works, and is the simplest that works.Thanks!
Tzafrir
+1  A: 
class A {
  // ...
  template <typename T>
  operator T*() const
  {
    // ...
  }
  // ...
};
Corwin
+2  A: 

While Klaim told you how, implicit conversions to pointers of T may lead to subtile bugs - so please don't do this in production code.
Explicitly taking the address via the & operator avoid these bugs and says more clearly what your intent was.

Also note that your assignment operator looks, lets say unusual. See the C++ FAQ lite entry for more details.

Georg Fritzsche
I agree. This was as a head-in-the-wall exercise.
Tzafrir