C++ 实现 类似 c# 扩展方法

辛苦找到的怕到时候帖子没了记录一下
原贴https://blog.csdn.net/coconut9325/article/details/78979100

这是关于 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 
 
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++根本不需要扩展方法,因为用它能实现扩展方法。

你可能感兴趣的:(问题处理,学习记录,c++)