I am trying to set the fields inside struct dynamically using templates. I have wrote the two approaches in the code. Both methods don't work saying no member named t.age.
How would I be able to set the fields dynamically? Any help is appreciated.
#include <iostream>
using namespace std;
struct hello {
string name;
};
struct bye {
int age;
};
template <typename T>
void printHello(string key) {
T t;
if (key == "HELLO") {
t.name = "John";
}
else {
t.age = 0;
}
}
template <typename T>
T setStruct(T t) {
if (typeid(t) == typeid(hello)) {
t.name = "John";
}
else {
t.age = 0;
}
return t;
}
int main() {
//printHello<hello>("HELLO"); // ERROR: no member named t.age
hello h;
h = setStruct(h); // ERROR: no member named t.age
return 0;
}