【问题标题】:Getting template type at runtime在运行时获取模板类型
【发布时间】:2016-01-05 07:52:29
【问题描述】:

我有以下方法,它获取 C 样式结构的向量并一次处理一个元素。

我希望在不复制代码的情况下扩展它以接收更多类型的结构。

由于所有类型的结构都将包含相同的字段名称,因此使用模板实现这一新要求将是最优雅的。

但是,我无法决定如何将第二个参数传递给write_db 函数;该参数是每个结构类型的枚举 - 是否有任何选项可以在运行时获取它?

enum policy_types { 
    POLICY_TYPE_A,
    POLICY_TYPE_B,
    ...
}; 

// old implementation - suitable for single struct only
int policyMgr::write_rule(std::vector <struct policy_type_a> & list) { 
    //conduct boring pre-write check
    //...

    for (auto & item : list ) { 
        int ret = write_db(item.key1, POLICY_TYPE_A_ENUM, &item.blob);
}

//new implementation - suitable for multiple structs. 
template <POLICY>
int policyMgr::write_rule(std::vector <POLICY> & list) { 
    for (auto & item : list ) { 
        int ret = write_db(item.key1, type(POLICY) /* how can i get enum according to template type */, &item.blob);
}

我曾考虑将枚举值添加为每个 struct 实例的常量,但我希望找到一种不需要更改基本结构格式的更好方法。

【问题讨论】:

    标签: c++ templates struct


    【解决方案1】:

    如果不想添加成员,可以提供“traits”类型。

    template<typename P>
    struct PolicyTraits {};
    
    template<>
    struct PolicyTraits<policy_type_a> 
    {
        static enum { Type = POLICY_TYPE_A };
    };
    
    template<>
    struct PolicyTraits<policy_type_b> 
    {
        static enum { Type = POLICY_TYPE_B };
    };
    
    template <typename A>
    int policyMgr::write_rule(const std::vector<A> & list) { 
        for (const auto & item : list ) { 
            int ret = write_db(item.key1, PolicyTraits<A>::Type, &item.blob);
        }
    }
    

    【讨论】:

    • 是的,这是更优雅的(和类似 C++ 标准库的)方法:与我的解决方案不同,它不会污染 A 类。加一。
    • 我会避免在特征/策略中为 value 使用名称 type
    • 但这不适用于运行时!如果向量由基本策略类特化并包含派生的策略子类型...模板将仅接收其向量的特化特征
    • @barney 如果向量包含A,则它包含A,而不是A 的子类型。
    【解决方案2】:

    每个类都有一个类型字段POLICY-able(如果你明白我的意思的话),其中foo就是一个例子:

    struct foo
    {
        /*your other bits*/
        static const policy_types type = POLICY_TYPE_whatever; /*older standards
                                      might require definition in a source file */.
    };
    

    然后酌情使用write_db(item.key1, POLICY::type)

    【讨论】:

      猜你喜欢
      • 2017-11-08
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多