Skip to content

Instantly share code, notes, and snippets.

@pqnelson
Last active August 29, 2015 14:05
Show Gist options
  • Save pqnelson/029ff6cccb96cb06beb3 to your computer and use it in GitHub Desktop.
Save pqnelson/029ff6cccb96cb06beb3 to your computer and use it in GitHub Desktop.
// $ g++ -std=c++11 object.cpp
// $ ./a.out
// Object@0x00d01010
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip> // for setw, setfill
#include "types.hpp"
#include "object.hpp"
namespace Lisp {
std::string Object::getClass() const {
return type(*this); // typeid(*this).name();
}
hash_t Object::hashCode() const {
hash_t result = reinterpret_cast<hash_t>(this);
return result;
}
std::string Object::toString() const {
std::ostringstream oss; // create a stringstream
std::string s; // create a string
hash_t hash = hashCode();
// this takes the value of this (the memory address), converts it to
// the hexadecimal textual representation, and puts it in the stream
oss << getClass()
<< "@"
<< std::hex
<< std::setfill('0')
<< std::setw(sizeof(hash_t))
<< hash;
// Get a std::string from the stream
s = oss.str();
return s;
}
}
int main()
{
Lisp::Object *o = new Lisp::Object();
std::string s = o->toString();
// Display the string
std::cout << s << std::endl;
}
#ifndef LISP_OBJECT_HPP
#define LISP_OBJECT_HPP
#include <string>
#include "types.hpp"
namespace Lisp {
// c.f. http://stackoverflow.com/q/8737019
class Object {
public:
virtual std::string getClass() const;
virtual hash_t hashCode() const;
virtual std::string toString() const;
};
}
#endif
#ifndef LISP_TYPES_HPP
#define LISP_TYPES_HPP
#include <typeinfo>
typedef std::size_t hash_t;
/* begin demangle code */
// c.f. http://stackoverflow.com/q/281818
std::string demangle(const char* name);
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
// enable c++11 by passing the flag -std=c++11 to g++
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return (status==0) ? res.get() : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif // __GNUG__
#endif // LISP_TYPES_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment