c++ - 使用模板 C++ 动态设置结构

标签 c++ templates 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;
}

最佳答案

printHello 将永远无法工作,因为您想对运行时字符串值执行编译时分支。

setStruct 更接近可能的解决方案,但是 typeid 返回一个运行时值 - 您需要一个编译时分支谓词以便有条件地编译.name.age 访问权限。

在 C++17 中,您可以使用 if constexprstd::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/

相关文章:

c++ - 有什么方法可以让 Eclipse 自动实现纯虚函数?

c++ - 在 C++ 中使用 continue 语句打印字符

c++ - 绘制圆弧并覆盖boundingRect()、shape()

c# - 用 C# 对象属性值替换 html 模板中的项目

c++ - 如何为与其类内联创建的对象提供模板参数?

c++ - auto_ptr 的动态内存分配

c++ - 通过递归得到数字 42

c++ - 将 enable_if 与两个级别的模板一起使用

C++ 如何创建从抽象类继承的对象的动态数组?

c# - 动态 linq 中的 Regex.IsMatch()