2014-04-26 22 views

回答

3

可以創建爲每個需要比較的比較函數,然後通過合適的函數作爲參數向稍長代碼塊(包裝在一個適當定義的功能)

作爲一個例子,考慮在函數(myFunc)接收2個整數(ab) 的假設情況下並處理它們。處理步驟除了在參數上完成的比較類型之外是相似的。我們通過提供myFunc右側工具來解決此問題,以供比較。

#include <iostream> 
using namespace std; 

bool comp1(int a, int b) { 
    return a > b; 
} 

bool comp2(int a, int b) { 
    return a < b; 
} 

void myFunc(int a, int b, bool (*myComp)(int, int)) { 
    bool res = myComp(a, b); 
    cout << "value : " << res << endl; 
} 
int main() 
{ 
    myFunc(1, 2, comp1); //use > 
    myFunc(1, 2, comp2); //use < 
    return 0; 
} 

顯然,comp1comp2是2個不同的比較器。根據要求我們將其中一個傳遞給myFunc<>)。

最好的事情是,你的比較現在可以像你想的那樣複雜,並且myFunc不理會複雜性。

+0

謝謝,但不幸的是,似乎並沒有在我的環境中工作。你知道其他方法嗎? – whitebloodcell

+0

@whitebloodcell在您的環境中,這種「不起作用」的限制是什麼? –

+0

@whitebloodcell沒有關於'mql5'的信息,但是其中一種解決方法可能是集體討論,並確保「冗長的代碼塊」是非常必要的。也許你可以用一種依賴於操作符的部分來重構代碼。 – axiom

1

通行證在「比較器」是一個函數或仿函數,在這種情況下我使用在functional頭定義的std::lessstd::greater函子,也有或多或少的所有運營商定義的函子。

#include <iostream> 
#include <functional> 

template<typename Comparator> 
void do_something(Comparator comp) 
{ 
    int a = 1; 
    int b = 2; 

    if (comp(a, b)) { 
     std::cout << "expression was true" << std::endl; 
    } else { 
     std::cout << "expression was not true" << std::endl; 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    do_something(std::greater<int>()); 
    do_something(std::less<int>()); 
} 

輸出:

expression was not true 
expression was true 
+0

在C++中這是一種有效的方法,但不幸的是MQL5不支持類模板/複雜模板形式參數(即函數/函子)。 – manlio

2

MQL4編碼你沒有指針功能/模板。 MQL5有模板,但正式的參數類型是只有內置或基本的用戶定義類型

你可以嘗試這樣的:

enum COMPARATOR 
{ 
    C_EQUAL = 0, 
    C_LESS = 1, 
    C_GREATER = -1 
    C_AT_MOST = 2, 
    C_AT_LEAST = -2, 
}; 

bool cmp(int a, int b, COMPARATOR c) 
{ 
    switch (c) 
    { 
    case C_LESS:  return a < b; 
    case C_AT_MOST: return a <= b; 
    case C_EQUAL: return a == b; 
    case C_AT_LEAST: return a >= b; 
    case C_GREATER: return a > b; 
    } 

    Alert("INTERNAL ERROR: UNKNOWN COMPARISON"); 
    return false; 
} 

void a_function(COMPARATOR c) 
{ 
    if (cmp(MathRand(), 13, c)) 
    Print("BOOM"); 

    // *** If you need the "opposite" of c *** you can write: 
    if (cmp(Time[0], Time[1], COMPARATOR(-c)) 
    Alert("DONE"); 
} 

這不是優雅,但它是有效的。

相關問題