Back to index

texmacs  1.0.7.15
blackbox.hpp
Go to the documentation of this file.
00001 
00002 /******************************************************************************
00003 * MODULE     : blackbox.hpp
00004 * DESCRIPTION: For hiding the implementation of a type
00005 * COPYRIGHT  : (C) 2005  Joris van der Hoeven
00006 *******************************************************************************
00007 * This software falls under the GNU general public license version 3 or later.
00008 * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
00009 * in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
00010 ******************************************************************************/
00011 
00012 #ifndef BLACKBOX_H
00013 #define BLACKBOX_H
00014 #include "basic.hpp"
00015 
00016 class blackbox_rep: public abstract_struct {
00017 public:
00018   inline blackbox_rep () {}
00019   inline virtual ~blackbox_rep () {}
00020   virtual int get_type () = 0;
00021   virtual bool equal (blackbox_rep* ptr) = 0;
00022   virtual tm_ostream& display (tm_ostream& out) = 0;
00023 };
00024 
00025 class blackbox {
00026 public:
00027 ABSTRACT_NULL(blackbox);
00028 };
00029 ABSTRACT_NULL_CODE(blackbox);
00030 
00031 template<class T>
00032 class whitebox_rep: public blackbox_rep {
00033 public:
00034   T data;
00035 public:
00036   inline whitebox_rep (const T& data2): data (data2) {}
00037   inline ~whitebox_rep () {}
00038   inline int get_type () { return type_helper<T>::id; }
00039   inline bool equal (blackbox_rep* ptr) {
00040     return ptr != NULL && ptr->get_type () == type_helper<T>::id &&
00041            ((whitebox_rep<T>*) ptr)->data == data; }
00042   inline tm_ostream& display (tm_ostream& out) { return out << data; }
00043 };
00044 
00045 inline bool operator == (blackbox bb1, blackbox bb2) {
00046   if (is_nil (bb1)) return is_nil (bb2);
00047   else return bb1->equal (bb2.rep); }
00048 inline bool operator != (blackbox bb1, blackbox bb2) {
00049   if (is_nil (bb1)) return !is_nil (bb2);
00050   else return !bb1->equal (bb2.rep); }
00051 inline tm_ostream& operator << (tm_ostream& out, blackbox bb) {
00052   if (is_nil (bb)) return out << "nil";
00053   else return bb->display (out); }
00054 
00055 inline int
00056 type_box (blackbox bb) {
00057   return is_nil (bb)? 0: bb->get_type ();
00058 }
00059 
00060 template<class T> blackbox
00061 close_box (const T& data) {
00062   return tm_new<whitebox_rep<T> > (data);
00063 }
00064 
00065 template<class T> T
00066 open_box (blackbox bb) {
00067   ASSERT (type_box (bb) == type_helper<T>::id, "type mismatch");
00068   return ((whitebox_rep<T>*) bb.rep) -> data;
00069 }
00070 
00071 #endif // BLACKBOX_H