在 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++根本不需要擴展方法,因爲用它能實現擴展方法。