My Computer Programs

(C++) any class

steloflute 2013. 2. 7. 01:46

similar to boost::any

There are times when a generic (in the sense of general as opposed to template-based programming) type is needed: variables that are truly variable, accommodating values of many other more specific types rather than C++'s normal strict and static types.

 

class any {
public:
  any(): content(0) {}
  template <typename T>
  any(const T &value): content(new holder<T>(value)) {}
  ~any() {
    delete content;
    content = 0;
  }
  template <typename T>
  T cast() {
    return static_cast<holder<T> *>(content)->held;
  }
private:
  class placeholder {
  public:
    virtual ~placeholder() {}
  };

  template <typename T>
  class holder: public placeholder {
  public:
    holder(const T &value): held(value) {}
    T held;
  };
  placeholder *content;
};

 

 

 

 

 

'My Computer Programs' 카테고리의 다른 글

My repositories on Bitbucket  (0) 2013.03.14
The Paren Programming Language  (0) 2013.02.24
(C++) pfcalc: Postfix Calculator  (0) 2013.01.28
DrClojure  (0) 2012.12.23
(Java) get web page, KOSPI200 시세 얻기  (0) 2012.12.11