在运行时获取模板类型

时间:2016-01-05 07:52:30

标签: c++ templates struct

我有以下方法获取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实例添加枚举值作为常量,但我希望找到一个更好的方法,不需要更改我的基本结构格式。

2 个答案:

答案 0 :(得分:9)

如果您不想添加会员,您可以提供&#34;特质&#34;类型。

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);
    }
}

答案 1 :(得分:3)

每个类POLICY都有一个类型字段 - 能够(如果你理解了我的意思),其中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)

相关问题