C++ 在运行时获取模板类型
我有下面的方法,它获取C风格结构的向量,并一次处理一个元素 我希望在不复制代码的情况下扩展它以接收更多类型的结构 由于所有类型的结构都将包含相同的字段名,因此使用模板实现这一新需求将是最优雅的 但是,我无法决定如何将第二个参数传递给C++ 在运行时获取模板类型,c++,templates,struct,C++,Templates,Struct,我有下面的方法,它获取C风格结构的向量,并一次处理一个元素 我希望在不复制代码的情况下扩展它以接收更多类型的结构 由于所有类型的结构都将包含相同的字段名,因此使用模板实现这一新需求将是最优雅的 但是,我无法决定如何将第二个参数传递给write\u db函数;该参数为每结构类型枚举,运行时是否有任何选项获取该参数 enum policy_types { POLICY_TYPE_A, POLICY_TYPE_B, ... }; // old implementation
write\u 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);
}
enum策略类型{
政策类型(A),,
政策类型,
...
};
//旧实现-仅适用于单个结构
int policyMgr::write_规则(std::vector&list){
//进行预写检查
//...
对于(自动项目:列表){
int ret=write_db(item.key1、POLICY_TYPE_A_ENUM和item.blob);
}
//新实现-适用于多个结构。
模板
int policyMgr::write_规则(std::vector&list){
对于(自动项目:列表){
int ret=write_db(item.key1,type(POLICY)/*如何根据模板类型*/,&item.blob获取枚举);
}
我曾考虑为每个结构实例添加枚举值作为常量,但我希望找到一种不需要更改基本结构格式的更好方法。在每个类上都有一个类型字段,该字段是
策略
-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\u db(item.key1,POLICY::type)
。如果不想添加成员,可以提供“traits”类型
模板
结构特性{};
模板
结构策略特征
{
静态枚举{Type=POLICY_Type_A};
};
模板
结构策略特征
{
静态枚举{Type=POLICY_Type_B};
};
模板
int policyMgr::write_规则(const std::vector&list){
对于(常量自动&项:列表){
int ret=write_db(item.key1,policytracts::Type,&item.blob);
}
}
是的,这是更优雅的(和C++标准库类似的)方法:与我的解决方案不同,它不会污染A
类。加上一个。我会避免traits/policy中的值使用名称type
。但这在运行时不起作用!如果向量按基本策略类进行专门化,并且包含派生策略子类型…模板将只接收其向量的专门化trait@barney如果向量包含A
,则它包含A
,而不是A
的子类型。
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);
}
}