1 /**
2 * @file mystring.cpp Example of extending GiNaC: writing new classes
3 */
4 #include <iostream>
5 #include <string>
6 #include <stdexcept>
7 #ifdef IN_GINAC
8 #include "ginac.h"
9 #else
10 #include <ginac/ginac.h>
11 #endif
12 using namespace std;
13 using namespace GiNaC;
14
15 class mystring : public basic
16 {
17 GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
18 public:
19 mystring(const string &s);
20 ex eval() const override;
21 private:
22 string str;
23
24 protected:
25 void do_print(const print_context &c, unsigned level = 0) const;
26
27 };
28
GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring,basic,print_func<print_context> (& mystring::do_print))29 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
30 print_func<print_context>(&mystring::do_print))
31
32 // ctors
33 mystring::mystring() { }
mystring(const string & s)34 mystring::mystring(const string &s) : str(s) { }
35
36 // comparison
compare_same_type(const basic & other) const37 int mystring::compare_same_type(const basic &other) const
38 {
39 const mystring &o = static_cast<const mystring &>(other);
40 int cmpval = str.compare(o.str);
41 if (cmpval == 0)
42 return 0;
43 else if (cmpval < 0)
44 return -1;
45 else
46 return 1;
47 }
48
49 // printing
do_print(const print_context & c,unsigned level) const50 void mystring::do_print(const print_context &c, unsigned level) const
51 {
52 // print_context::s is a reference to an ostream
53 c.s << '\"' << str << '\"';
54 }
55
56 /**
57 * evaluation: all strings automatically converted to lowercase with
58 * non-alphabetic characters stripped, and empty strings removed
59 */
eval() const60 ex mystring::eval() const
61 {
62 string new_str;
63 for (size_t i=0; i<str.length(); i++) {
64 char c = str[i];
65 if (c >= 'A' && c <= 'Z')
66 new_str += tolower(c);
67 else if (c >= 'a' && c <= 'z')
68 new_str += c;
69 }
70
71 if (new_str.length() == 0)
72 return 0;
73 else
74 return mystring(new_str).hold();
75 }
76
main(int argc,char ** argv)77 int main(int argc, char** argv)
78 {
79 ex e = mystring("Hello, world!");
80 cout << is_a<mystring>(e) << endl;
81 cout << ex_to<basic>(e).class_name() << endl;
82 cout << e << endl;
83 ex another = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
84 cout << another << endl;
85 return 0;
86 }
87