2 * @file mystring.cpp Example of extending GiNaC: writing new classes
9 #include <ginac/ginac.h>
10 using namespace GiNaC;
12 class mystring : public basic
14 GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
16 mystring(const string &s);
17 mystring(const char *s);
18 ex eval(int level) const;
24 void do_print(const print_context &c, unsigned level = 0) const;
28 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
29 print_func<print_context>(&mystring::do_print))
32 mystring::mystring() { }
33 mystring::mystring(const string &s) : str(s) { }
34 mystring::mystring(const char *s) : str(s) { }
37 int mystring::compare_same_type(const basic &other) const
39 const mystring &o = static_cast<const mystring &>(other);
40 int cmpval = str.compare(o.str);
49 // archiving/unarchiving
50 void mystring::read_archive(const archive_node &n, lst &sym_lst)
52 inherited::read_archive(n, sym_lst);
53 n.find_string("string", str);
56 void mystring::archive(archive_node &n) const
58 inherited::archive(n);
59 n.add_string("string", str);
62 ex mystring::unarchive(const archive_node &n, lst &sym_lst)
64 return (new mystring(n, sym_lst))->setflag(status_flags::dynallocated);
68 void mystring::do_print(const print_context &c, unsigned level) const
70 // print_context::s is a reference to an ostream
71 c.s << '\"' << str << '\"';
75 * evaluation: all strings automatically converted to lowercase with
76 * non-alphabetic characters stripped, and empty strings removed
78 ex mystring::eval(int level) const
81 for (size_t i=0; i<str.length(); i++) {
83 if (c >= 'A' && c <= 'Z')
84 new_str += tolower(c);
85 else if (c >= 'a' && c <= 'z')
89 if (new_str.length() == 0)
92 return mystring(new_str).hold();
95 int main(int argc, char** argv)
97 ex e = mystring("Hello, world!");
98 cout << is_a<mystring>(e) << endl;
99 cout << ex_to<basic>(e).class_name() << endl;
101 ex another = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
102 cout << another << endl;