python_boost学习笔记8,重载函数

这里学习了

  1. 重载使用类似于函数指针的概念,让python在调用的时候知道应该调用哪一个函数
    void (Example::*d1)() = &Example::doit;
    std::string (Example::*d2)(unsigned int) = &Example::doit;
    void (Example::*d3)(std::string) = &Example::doit
    生成3个函数表示 d1 d2 d3分别表示对应的重载函数

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(fun_,fun,m,n)
def(“fun_name”, fun, fun_())
n:表示最少几个参数
m:表示最多几个参数
实列在c++代码中

#include <sstream>

#include <string>



class Example {

        public:

                Example()

                {}



                void doit() { mS = "void"; }

                std::string doit(unsigned int i)

                {

                        std::stringstream s;

                        s << i;

                        mS = s.str();

                        return mS;

                }

                void doit(std::string s) { mS = s; }



                int makeIt(std::string s, int n=1, std::string t="")

                {

                        std::stringstream u;

                        for (unsigned int i=0; i<n; ++i)

                                u << s;

                        mS = u.str() + t;

                        return n + ( t.size() > 0 ? 1 : 0 );

                }



                std::string print() const { return mS; } //会被python 的print函数 默认调用

        private:

                std::string mS;

};



#include <boost/python.hpp>

using namespace boost::python;



//一个模板,将makeIt 封装成重载函数,1,3表示最少1个参数,最多3个参数
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(makeIt_overloads, makeIt, 1, 3) 



BOOST_PYTHON_MODULE(boost_eg)

{

        //这里类似于做一个函数指针的方式,告诉python 如何调用重载函数
        void        (Example::*d1)()             = &Example::doit; 

        std::string (Example::*d2)(unsigned int) = &Example::doit;

        void        (Example::*d3)(std::string)  = &Example::doit;



        class_<Example>("Example")

                .def("__str__", &Example::print)

                .def("doit", d1) 

                .def("doit", d2)

                .def("doit", d3)

                .def("makeIt", &Example::makeIt, makeIt_overloads()) //另一种重载

                ;

}

python 代码:

#!/usr/bin/env python
from boost_eg import Example
e = Example()
e.doit(); print (e)
print (e.doit(2))
e.doit("Hallo"); print (e)
print ("------")
print (e.makeIt("xxx"), e)
print (e.makeIt("abc", 2), e)
print (e.makeIt("xyz", 3, "abc"), e)

运行结果:

void
2
Hallo
------
1 xxx
2 abcabc
4 xyzxyzxyzabc
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值