pse*_*udo 0 c++ templates struct dynamic
我正在尝试使用模板动态设置struct中的字段.我在代码中写了两种方法.这两种方法都不起作用说no member named t.age.我怎么能动态设置字段?任何帮助表示赞赏.
#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;
}
Run Code Online (Sandbox Code Playgroud)
printHello 将无法工作,因为您希望在运行时字符串值上执行编译时分支.
setStruct更接近于一个可能的解决方案,但同样,typeid返回一个运行时值 - 您需要一个编译时分支谓词,以便有条件地编译.name或.age访问.
在C++ 17中,您可以使用if constexpr和轻松解决此问题std::is_same_v:
template <typename T>
T setStruct(T t) {
if constexpr(std::is_same_v<T, hello>) {
t.name = "John";
}
else {
t.age = 0;
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
有关" vs "的更多信息,请点击此处if constexprif
请注意,您可以通过提供多个重载来简单地解决您的特定示例:
hello setStruct(hello t)
{
t.name = "John";
return t;
}
bye setStruct(bye t)
{
t.age = 0;
return t;
}
Run Code Online (Sandbox Code Playgroud)