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
但嬰兒的步驟時間。現在我只想知道是否可以分配和存儲一個表達式,以及該表達式中引用的任何變量/函數。
這可能嗎?
是的,使用表達式模板是可行的。在[這個答案](http://stackoverflow.com/questions/17868718/variadic-template-operator/17869231#17869231)我談了一些關於表達式模板和它背後的想法。你可以使用它來解決你的問題(順便說一下,它會有一大塊代碼)。 – Synxis