c++ - 如何根据另一个模板参数将模板参数固定为一个枚举类?
问题描述
我有以下代码,到目前为止,我们有衣服和鞋类。但是将来可能会有更多的项目对象类型。该类Foo
是模板化的Object
,它的成员函数对于两者都是相同的eClothes
,eFootwear
但在实际代码中会进一步模板化。
有没有办法对方法的实现进行重复数据删除order
?因为有一个一对一的映射
- Object::clothes -> eClothes
- Object::footwear -> eFootwear
.. 有什么技术可以用来修复order
基于的模板参数type
吗?这样一个类实例化只接受其相应类型的命令,否则是编译时错误?
#include<iostream>
enum class Object{
clothes,
footwear,
};
enum class eClothes{
shirt,
};
enum class eFootwear{
flipflop,
};
template <Object type>
class Foo{
public:
template<eClothes clothkind>
void order(){
std::cout << "hey\n";
}
template<eFootwear footwearkind>
void order(){
std::cout << "hey\n";
}
};
int main(){
Foo<Object::clothes> foo_clothes;
Foo<Object::footwear> foo_footwear;
foo_clothes.order<eClothes::shirt>();
foo_footwear.order<eFootwear::flipflop>();
}
解决方案
定义映射到其值类型的特征。Object
像:
template <Object value> struct ObjectTraits;
template <> struct ObjectTraits<Object::clothes>
{
using type = eClothes;
};
template <> struct ObjectTraits<Object::footwear>
{
using type = eFootwear;
};
template <Object type>
class Foo{
public:
using Kind = typename ObjectTraits<type>::type;
template<Kind kind>
void order(){
std::cout << "hey\n";
}
};
为了简化一点 - 你可以使用宏:
template <Object value> struct ObjectTraits;
#define OBJECT_TRAITS(value, kind) \
template <> struct ObjectTraits<Object::value> { \
using type = kind; \
}
OBJECT_TRAITS(clothes , eClothes);
OBJECT_TRAITS(footwear, eFootwear);
推荐阅读
- ruby - Jekyll 博客主题现在在 GitLab 页面上显示博客文章
- php - 正则表达式匹配单词边界与引号
- python - 我应该如何使用 cnn 提高人脸识别的准确性?
- mongodb - 更新对象mongodb下的多个键值
- postgresql - 使用 Nifi 将数据源作为 teradata 加载到目标作为 Postgres 表的最佳方法是什么
- ubuntu - 无法卸载角度/cli
- migration - Openerp7 迁移到 odoo 11
- java - startForeground 的错误通知
- xcode - CMD + r 在 Mojave (10.14.2) 的 Xcode 版本 10.1 中不起作用
- apache-spark - PySpark - 一种更有效的计算常见元素的方法