【问题标题】:Inheriting traits in c++在 C++ 中继承特征
【发布时间】:2019-12-12 15:59:30
【问题描述】:

我正在 c++ 中创建一个特征,它将我制作的另一个特征作为模板输入。 但是,当我运行此代码时,会出现以下编译器错误:

错误:模板参数的数量错误(1,应该是 2)模板 a>

代码如下:

enum class Unit { km, m, cm };


template<int v, Unit u>
struct Measure
{
public:
    static const int value = v;
    static const Unit unit = u;
};


template< Measure<int v, Unit u> a>
struct Measure_add
{
public:
    static const int value = a::value;
    static const Unit unit = a::unit;
};

用法应该是:

std::cout << Measure_add< Measure<4, Unit::m> >::value << std::endl;

这应该给出:

4

【问题讨论】:

    标签: c++ templates struct traits


    【解决方案1】:

    不知道这是什么意思:

    template< Measure<int v, Unit u> a>
    

    你可能想要这个:

    template< typename  a>
    struct Measure_add
    {
    public:
        static const int value = a::value;
        static const Unit unit = a::unit;
    };
    

    现在你可以通过

    实例化它了
    using m_add = Measure_add< Measure<4,Unit::m> >;
    

    【讨论】:

    • 这是有道理的,但是我希望用法是这样的:` std::cout >::value 类型
    • @suitendaal erm 不,是的。您用作参数的类型可以是Measure 的实例化,请参阅编辑
    【解决方案2】:

    Measure_add 可以通过以下方式从Measure 继承:

    template<class>
    struct Measure_add;
    
    template<int v, Unit u>
    struct Measure_add<Measure<v, u>> : Measure<v, u> {};
    
    static_assert(Measure_add<Measure<4, Unit::m>>::value == 4);
    

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 2015-03-23
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多