继承 c++ 中的特征

Inheriting traits in c++

本文关键字:特征 c++ 继承      更新时间:2023-10-16

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

错误

:模板参数数错误(1,应为 2( 模板<\测量<\int v,单位 u> 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;

这应该给出:

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

不确定这是什么意思:

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