首页 > 解决方案 > 如何根据另一个模板参数将模板参数固定为一个枚举类?

问题描述

我有以下代码,到目前为止,我们有衣服和鞋类。但是将来可能会有更多的项目对象类型。该类Foo是模板化的Object,它的成员函数对于两者都是相同的eClotheseFootwear但在实际代码中会进一步模板化。

有没有办法对方法的实现进行重复数据删除order?因为有一个一对一的映射

.. 有什么技术可以用来修复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>();
}

标签: c++templatesenumsc++17sfinae

解决方案


定义映射到其值类型的特征。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);


推荐阅读