【问题标题】:How to fix template parameter as one enum class based on another template parameter?如何基于另一个模板参数将模板参数固定为一个枚举类?
【发布时间】:2020-12-11 07:54:53
【问题描述】:

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

有没有办法对方法 order 的实现进行重复数据删除?由于存在一对一的映射

  • Object::clothes -> eClothes
  • Object::footwear -> eFootwear

.. 有没有什么技术可以用来修复基于typeorder 的模板参数?这样一个类实例化只接受其对应类型的命令,否则它是一个编译时错误?

#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++ templates enums c++17 sfinae


    【解决方案1】:

    定义将Object 映射到其值类型的traits。喜欢:

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

    【讨论】:

    • 谢谢!我正在摆弄创建一个基本结构,然后从它派生出每个派生结构都将具有 typedef 的位置。但是派生的类型从基础看不到。特质确实是我一直在寻找的东西。 \\ 在Foo&lt;eClothes&gt;{}.order&lt;eClothes::shirt&gt;(); 中,我可以调用方法、传递等方法的对象实例化在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多