In C ++, how to create a conversion from T to T *?

In preparation for the OOP exam, I liked the fact that g ++ compiled the following code (without creating an instance), although it seemed to make no sense:

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

Then I set the task to make this instance 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 templates to work, except for the line

T* p = t;

My question is: which operator or constructor will make this line? He currently gives me "error: cannot convert 'A to' A * on initialization"

+3
source share
5 answers

This is a completely pointless line.

But to make it compiled, you can provide a conversion operator:

operator A* () { return 0; }

, , .

+3

?

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

, , .

+7

Klaim , T subtile, , , . &, , .

, , , . . ++ FAQ lite entry.

+2
class A {
  // ...
  template <typename T>
  operator T*() const
  {
    // ...
  }
  // ...
};
+1

C/++ , ,

T* p = &t;
0

Source: https://habr.com/ru/post/1735715/


All Articles