2017-05-29 52 views
1

我編寫了用於設置頂點屬性的幫助函數。正如你所看到的,3個函數基本上是相同的,只是每個函數都設置了不同的頂點成員變量。由於它違背了DRY原則,看起來很醜,所以我想將它們結合起來。避免每個成員變量的重複函數

void setPositions(const int offset, const sf::Vector2f (&positions)[vertexCount]) { 
    int index = ensureSizeAndGetIndex(offset); 
    for(int i = 0; i < vertexCount; i++) { 
     vertices[index + i].position = positions[i]; 
    } 
} 

void setTexCoords(const int offset, const sf::Vector2f (&texCoords)[vertexCount]) { 
    int index = ensureSizeAndGetIndex(offset); 
    for(int i = 0; i < vertexCount; i++) { 
     vertices[index + i].texCoords = texCoords[i]; 
    } 
} 

void setColors(const int offset, const sf::Color (&colors)[vertexCount]) { 
    int index = ensureSizeAndGetIndex(offset); 
    for(int i = 0; i < vertexCount; i++) { 
     vertices[index + i].color = colors[i]; 
    } 
} 

事情我考慮:

    因爲他們不處理成員變量
  • 模板就不會在這裏工作
  • 我可以傳遞一個布爾標誌結合了前兩個函數其中變量的使用。但這對第三個功能無濟於事。
  • 我可以添加指針頂點類的成員變量和枚舉可供選擇,但這將是太多(性能)開銷
  • Lambdas也許,元編程也許?

只是會對這裏最乾淨的解決方案感興趣。

+1

爲什麼你認爲模板不能處理成員變量指針? –

+0

標識符不能用作模板參數。我正是這個意思。 – MorbZ

+0

你的意思是[this](https://wandbox.org/permlink/W1aA6GDB0T0ugbS3)? –

回答

2

如果texCoords,positioncolor是相同類型,解決方案非常簡單。類成員指針。

假設有問題的類看起來是這樣的:

class V { 
public: 

    int texCoords; 
    int position; 
    int color; 
}; 

然後你的成員函數每一個變爲提供相應的類成員指針的包裝。例如,setTexCoords變得

void setTexCoords(const int offset, const sf::Vector2f (&texCoords)[vertexCount]) { 
    setCommon(offset, texCoords, &V::texCoords); 
} 

另外兩個封裝類似於,和共用的代碼變爲:

void setCommon(const int offset, const sf::Vector2f (&texCoords)[vertexCount], 
       int V::*member) { 
    int index = ensureSizeAndGetIndex(offset); 
    for(int i = 0; i < vertexCount; i++) { 
     vertices[index + i].*member = texCoords[i]; 
    } 
} 

類成員的指針看起來像常規指針,它們共享相同的原理,但他們不要傳統的指針,並且有必要充分理解它們的工作方式。欲瞭解更多信息,請參閱您的C++書籍。

+0

通過正確使用模板,當成員類型不匹配時,該解決方案仍然可以工作。 –

+0

非常有幫助的答案。類成員指針似乎是合適的。 V的成員變量不具有相同的類型,但我認爲可以通過將setCommon設置爲函數模板來輕鬆解決。 – MorbZ