1

Is it possible to make it ?

For instance, consider the following code snippet:

#include <iostream>
using namespace std;

template <typename T> class A {
public:
  void print() {
    T var;
    cout << sizeof(var) << endl;
  }
};

int main() {
  A<int>* c = new A<int>;
  c->print();

  A<char>* d = reinterpret_cast<A<char>*>(c);
  d->print();
}

Is there a "danger" with this kind of pratice ?

4

2 回答 2

3

Yes, this would invoke undefined behaviour. A<char> and A<int> are entirely unrelated types. So it's no different to reinterpret-casting as a B.

In practice, it will probably work (at least for something this simple). But that doesn't mean that you can rely on it.

于 2012-06-02T14:34:15.010 回答
1

Is there a "danger" with this kind of pratice ?

This is an undefined behavior, as you are converting a pointer to a different type and then calling a function.
Remember that A<int> and A<char> are different types; don't get confused from the same name A.

Here is a good related article from Bjarne Stroustrup's web page.

于 2012-06-02T14:36:06.007 回答