I got a class, containing 20 structure elements in a classical C-Array. The elements form 0 to 5 belong to Type A, from 6 to 15 they belong to Type B and the rest belongs to Type C. For looping this elements, I designed three function templates. Here is a very simple example of my problem (I know, it makes no sense, butit only demonstrates what I want):
#include <iostream>
#include <string>
struct MyStruct {
int Value;
MyStruct() {
this->Value = 0;
}
MyStruct(int fValue) {
this->Value = fValue;
}
void PrintValue() { std::cout << "Value: " << std::to_string(this->Value) << std::endl; }
};
class MyClass {
private:
struct MyStruct valArr[20];
int aRange = 5;
int bRange = 10;
public:
MyClass() {
for (int i = 0; i < 20; i++) {
valArr[i] = MyStruct(i);
}
}
template<typename FUNCTION>
inline void LoopRangeA(FUNCTION f, bool GetIndex = false) {
for (int i = 0; i < aRange; i++) {
f(&this->valArr[i]);
}
}
template<typename FUNCTION>
inline void LoopRangeB(FUNCTION f) {
for (int i = aRange; i < bRange; i++) {
f(&this->valArr[i]);
}
}
template<typename FUNCTION>
inline void LoopRangeC(FUNCTION f) {
for (int i = bRange; i < 20; i++) {
f(&this->valArr[i]);
}
}
template<typename FUNCTION>
inline void LoopAll(FUNCTION f) {
for (int i = 0; i < 20; i++) {
f(&this->valArr[i]);
}
}
};
int main() {
MyClass Cls = MyClass();
Cls.LoopRangeA([](MyStruct* pStr) {pStr->PrintValue(); });
std::cout << "Application is finished. Press ENTER to exit..." << std::endl;
std::cin.get();
}
Well, that runs well. But sometimes, I also need the array-index of the element. As I still have lots of this function templates in my real programm, I try to avoid defining new functions but want to overload them or use an optional argument.
I tried this was, but it doesn't run (just show the difference):
template<typename FUNCTION>
inline void LoopRangeA(FUNCTION f, bool GetIndex = false) {
if (GetIndex) {
for (int i = 0; i < aRange; i++) {
f(&this->valArr[i], i);
}
}else {
for (int i = 0; i < aRange; i++) {
f(&this->valArr[i]);
}
}
}
int main() {
MyClass Cls = MyClass();
Cls.LoopRangeA([](MyStruct* pStr, int& i) {std::cout << "Index: " << std::to_string(i); pStr->PrintValue(); std::cout << "" << std::endl; }, true);
std::cout << "Application is finished. Press ENTER to exit..." << std::endl;
std::cin.get();
}
Does anybody has an idea, how to solve that problem without defining complette new function members?
Thank you in advance, Jan