2013-07-26 40 views
0

我創建了一個名爲binding_condition的模板類,以便我可以將條件的排列抽象爲單個對象。目前它與傳遞一個lambda以及任何需要檢查的變量一起工作,但是我發現這個lambda是誤導性的,因爲它需要捕獲我所引用的變量。構造函數爲布爾表達式,而不是結果

例如:

bool someVal = true; 
int h = 10; 
double p = 99.8; 
char c = 'C'; 

binding_condition<bool> bc(
    [] (bool b) 
{ return b; }, 
someVal); 

binding_condition<bool, int> bc2(
    [] (bool b, int i) 
{ return b && (i > 9); }, 
someVal, h); 

binding_condition<bool, int, double> bc3(
    [] (bool b, int i, double d) 
{ return b && (i > 9) && (d < 100); }, 
someVal, h, p); 

binding_condition<bool, int, double, char> bc4(
    [] (bool b, int i, double d, char c) 
{ return b && (i > 9) && (d < 100) && c == 'C'; }, 
someVal, h, p, c); 

這讓我抽象一些複雜的條件到一個單一的名字:

if (ThisComplexCondition) ... 
else if (ThisOtherComplexCondition ... 
... 

但是我想知道是否有辦法,無論是與表情模板或其他一些方法,以允許這樣的語法:

binding_condition<bool, int, double> ComplexCondition = myClass.isTrue() && someThing.id < 100 && someDouble > 30.2; 

我意識到上述表達式i不是特別有創意,但考慮到這下一個:

// analyzing chords in music to roman numeral notation, detect modulations, etc 

// isChordRelatedToKey (the chord can be made from the current key 

// isNeopolitan (the chord is a bii6 of the current key 
    // is major 
    // letter() is II/ii (ie C# major in C major is not a neapolitan, but Db major is) 

// isSecondaryDominant 
    // chord is major 
    // chord is dominant of next chord (requires a new temporary key of next chord 

// isSecondaryDiminished 
    // chord is diminished, and is the viio of the next chord 
// all other forms of secondary, which means a ii/V in C major is A minor, which is also the vi of the key, and the iii/IV is also A minor 

// nested secondary chords ie I - V - V/V - vii/V/V (C major, G major, D major, C# diminished) 

// isModulation 
    // the current string of chords is not related to the current Key anymore 

我想實現某種的statemachine的,包裝這些限制爲對象,並簡單地檢查,如:在

if (isModulation) ... 
if (isSecondary) ... // recursive 
if (isChordNoRelation) ... // some chord that makes no sense from previous string 

但嬰兒的步驟時間。現在我只想知道是否可以分配和存儲一個表達式,以及該表達式中引用的任何變量/函數。

這可能嗎?

+0

是的,使用表達式模板是可行的。在[這個答案](http://stackoverflow.com/questions/17868718/variadic-template-operator/17869231#17869231)我談了一些關於表達式模板和它背後的想法。你可以使用它來解決你的問題(順便說一下,它會有一大塊代碼)。 – Synxis

回答

0

lambda關閉有什麼問題,捕獲變量?你不需要讓它們作爲參數傳遞。在你的第一個例子,你可以這樣做:

bool someVal = true; 
int h = 10; 
double p = 99.8; 
char c = 'C'; 

auto bc4 = [&](){return someVal && (h > 9) && (p < 100) && c == 'C';}; 

//later: 
if(bc4()) 
{ 
    /*...*/ 
} 

,爲的Econd例如:

auto ComplexCondition = [&]() { return myClass.isTrue() && someThing.id < 100 && someDouble > 30.2;}; 

表達prodice關閉,通過參考捕捉提及的變量,所以值拉姆達進行評估時,關閉操作符()稱爲:

bool someVal = true; 
int h = 10; 
double p = 99.8; 
char c = 'C'; 

auto bc4 = [&](){return someVal && (h > 9) && (p < 100) && c == 'C';}; 

if(bc4()) //gives true 
{ /* ... */ } 

p *= 2; 
if (bc4()) {} //gives false, since p > 100 
相關問題