我正在尝试使用模板动态设置结构中的字段。我已经在代码中写了这两种方法。这两种方法都不起作用,说 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;
}
最佳答案
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;
}
更多信息 on "if constexpr
vs if
" here.
请注意,您的特定示例可以通过提供多个重载来简单地解决:
hello setStruct(hello t)
{
t.name = "John";
return t;
}
bye setStruct(bye t)
{
t.age = 0;
return t;
}
关于c++ - 使用模板 C++ 动态设置结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401578/