2017-05-29 54 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