C++扩展方法

在 stackoverflow 看到了一点精华,想要记录下来。

这是关于 C++ 扩展方法的思路:

1.使用定义operator来连接一个struct并调用struct的构造,这个struct的构造即为扩展方法的实现。

(个人感觉不利于扩展方法中多参数,重载的实现。这部分代码不贴出来了,大家根据提供的思路很快也能架构出原型)

使用方法:var result = a | extension::trim();

2.使用扩展class来接收需要扩展方法的对象,接着在扩展class中实现扩展方法。

(利于扩展方法多参数的传递,使用时要外包一层)

使用方法:var result = extension(a).trim();

3.使用定义operator来连接一个扩展class,扩展class接收需要扩展方法的对象,接着在扩展class中实现扩展方法。

使用方法:var result = a<-trim();

#include <iostream>

using namespace std;


class regular_class {

    public:

        void simple_method(void) const {
            cout << "simple_method called." << endl;
        }

};


class ext_method {

    private:

        // arguments of the extension method
        int x_;

    public:

        // arguments get initialized here
        ext_method(int x) : x_(x) {

        }


        // just a dummy overload to return a reference to itself
        ext_method& operator-(void) {
            return *this;
        }


        // extension method body is implemented here. The return type of this op. overload
        //    should be the return type of the extension method
        friend const regular_class& operator<(const regular_class& obj, const ext_method& mthd) {

            cout << "Extension method called with: " << mthd.x_ << " on " << &obj << endl;
            return obj;
        }
};


int main()
{ 
    regular_class obj;
    cout << "regular_class object at: " << &obj << endl;
    obj.simple_method();
    obj<-ext_method(3)<-ext_method(8);
    return 0;
}

4.看了那么多是不是已经知道C++没有扩展方法了。

C++根本不需要扩展方法,因为用它能实现扩展方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值