Skip to content

Commit 7b1cc7f

Browse files
committed
Added overloading example
1 parent 1f974d9 commit 7b1cc7f

File tree

3 files changed

+75
-1
lines changed

3 files changed

+75
-1
lines changed

09-Overloading/overload.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <sstream>
2+
#include <string>
3+
4+
class Example {
5+
public:
6+
Example()
7+
{}
8+
9+
void doit()
10+
{
11+
mS = "void";
12+
}
13+
std::string doit(unsigned int i)
14+
{
15+
std::stringstream s;
16+
s << i;
17+
mS = s.str();
18+
return mS;
19+
}
20+
void doit(std::string s)
21+
{
22+
mS = s;
23+
}
24+
25+
int makeIt(std::string s, int n=1, std::string t="")
26+
{
27+
std::stringstream u;
28+
for (unsigned int i=0; i<n; ++i)
29+
u << s;
30+
mS = u.str() + t;
31+
return n + ( t.size() > 0 ? 1 : 0 );
32+
}
33+
34+
std::string print() const
35+
{ return mS; }
36+
private:
37+
std::string mS;
38+
};
39+
40+
#include <boost/python.hpp>
41+
using namespace boost::python;
42+
43+
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(makeIt_overloads, makeIt, 1, 3)
44+
45+
BOOST_PYTHON_MODULE(overload)
46+
{
47+
void (Example::*d1)() = &Example::doit;
48+
std::string (Example::*d2)(unsigned int) = &Example::doit;
49+
void (Example::*d3)(std::string) = &Example::doit;
50+
51+
class_<Example>("Example")
52+
.def("__str__", &Example::print)
53+
.def("doit", d1)
54+
.def("doit", d2)
55+
.def("doit", d3)
56+
.def("makeIt", &Example::makeIt, makeIt_overloads())
57+
;
58+
}

09-Overloading/overload.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/usr/bin/env python
2+
3+
from overload import Example
4+
5+
e = Example()
6+
7+
e.doit(); print e
8+
print e.doit(2)
9+
e.doit("Hallo"); print e
10+
11+
print "------"
12+
13+
print e.makeIt("xxx"); print e
14+
print e.makeIt("abc", 2); print e
15+
print e.makeIt("xyz", 3, "abc"); print e
16+

CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ ADD_SUBDIRECTORY(05-Inheritance)
1515
ADD_SUBDIRECTORY(06-VirtualFunctionsInPython)
1616
ADD_SUBDIRECTORY(07-Operators)
1717
ADD_SUBDIRECTORY(08-CallPolicies)
18-
#ADD_SUBDIRECTORY(09-Overloading)
18+
ADD_SUBDIRECTORY(09-Overloading)
1919
#ADD_SUBDIRECTORY(10-ObjectInterface)
2020
#ADD_SUBDIRECTORY(11-ExtractingObjects)
2121
ADD_SUBDIRECTORY(12-Embedding)

0 commit comments

Comments
 (0)