Zoh*_*r81 5 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);
}
Run Code Online (Sandbox Code Playgroud)
我想为每个struct实例添加枚举值作为常量,但我希望找到一个更好的方法,不需要改变我的基本结构格式.
mol*_*ilo 10
如果您不想添加成员,则可以提供"特征"类型.
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);
}
}
Run Code Online (Sandbox Code Playgroud)