Skip to content

Instantly share code, notes, and snippets.

@dmikurube
Created December 8, 2011 09:15
Show Gist options
  • Save dmikurube/1446532 to your computer and use it in GitHub Desktop.
Save dmikurube/1446532 to your computer and use it in GitHub Desktop.
Type-preserving operator new
// Test code of http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=6080813.
// Actually, it doesn't require to make type_identifier_to_string.
// The mapping can be obtained from a linker.
#include <map>
#include <string>
#include <typeinfo>
std::map<void *, char *> pointer_to_type_identifier;
std::map<void *, const std::type_info*> pointer_to_type_info;
std::map<char *, std::string> type_identifier_to_string;
template<class T>
class TYPE_IDENTIFIER {
public:
static char mDummy;
};
class NoVirtual {
private:
int a_value_;
};
class Base {
public:
virtual int func() { ; }
private:
int a_value_;
};
class Sub : public Base {
public:
virtual int func() { ; }
};
template<class T> char TYPE_IDENTIFIER<T>::mDummy = 0;
struct NewTrick {
template<class T>
T* operator* (T* pointer) {
pointer_to_type_identifier[pointer] = &TYPE_IDENTIFIER<T>::mDummy;
pointer_to_type_info[pointer] = &typeid(T());
return pointer;
}
};
#include <iostream>
#define new NewTrick() * new
#define FIND_AND_PRINT_TYPE_IDENTIFIER(p) std::cout << #p << ":" << type_identifier_to_string[pointer_to_type_identifier[((void *)(p))]] << std::endl;
#define FIND_AND_PRINT_TYPE_INFO(p) std::cout << #p << ":" << pointer_to_type_info[((void *)(p))]->name() << std::endl;
int main() {
type_identifier_to_string[&TYPE_IDENTIFIER<char>::mDummy] = "char";
type_identifier_to_string[&TYPE_IDENTIFIER<int>::mDummy] = "int";
type_identifier_to_string[&TYPE_IDENTIFIER<NoVirtual>::mDummy] = "NoVirtual";
type_identifier_to_string[&TYPE_IDENTIFIER<Base>::mDummy] = "Base";
type_identifier_to_string[&TYPE_IDENTIFIER<Sub>::mDummy] = "Sub";
int* x = new int;
char* y = new char;
Base* o = new Base;
NoVirtual* p = new NoVirtual;
int* z = new int;
Sub* q = new Sub;
FIND_AND_PRINT_TYPE_IDENTIFIER(x);
FIND_AND_PRINT_TYPE_IDENTIFIER(y);
FIND_AND_PRINT_TYPE_IDENTIFIER(o);
FIND_AND_PRINT_TYPE_IDENTIFIER(p);
FIND_AND_PRINT_TYPE_IDENTIFIER(z);
FIND_AND_PRINT_TYPE_IDENTIFIER(q);
FIND_AND_PRINT_TYPE_INFO(x);
FIND_AND_PRINT_TYPE_INFO(y);
FIND_AND_PRINT_TYPE_INFO(o);
FIND_AND_PRINT_TYPE_INFO(p);
FIND_AND_PRINT_TYPE_INFO(z);
FIND_AND_PRINT_TYPE_INFO(q);
delete q;
delete z;
delete p;
delete o;
delete y;
delete x;
}
@dmikurube
Copy link
Author

typeid() works.

x:int
y:char
o:Base
p:NoVirtual
z:int
q:Sub
x:FivE
y:FcvE
o:F4BasevE
p:F9NoVirtualvE
z:FivE
q:F3SubvE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment