约束模板参数顺序的更简单方法

A simpler way to constraint the order of the arguments of a template

本文关键字:更简单 方法 顺序 参数 约束      更新时间:2023-10-16

我想将芯片(IC)连接到微控制器。为此,我必须将微控制器的特定引脚连接到IC。据我所知,编译时的连接是使用模板:

template<int num_pin_a, int num_pin_b, int num_pin_c>
struct IC{
// ...
};

在本例中,我的 IC 有 3 个引脚:A、B 和 C。

这段代码的问题在于它有点容易出错。要创建一个IC,我必须写

IC<14, 10, 7> my_ic;

但是 14、10 和 7 的含义是什么?我无法读取此代码,但我想读取我的代码。当然,我可以使用宏或constexpr来避免幻数,因此我可以读取代码,但编译器不能。我希望我的编译器在犯错时通知我。

为了实现这一点,我编写了以下代码:

template<int n>
struct Pin_A{};
template<int n>
struct Pin_B{};
template<int n>
struct Pin_C{};
template<int num_pin_a, int num_pin_b, int num_pin_c>
IC<num_pin_a, num_pin_b, num_pin_c> ic(Pin_A<num_pin_a>, 
Pin_B<num_pin_b>, 
Pin_C<num_pin_c>)
{
return IC<num_pin_a, num_pin_b, num_pin_c>{};
}

当我想创建一个IC时,我必须编写以下代码:

auto my_ic = ic(Pin_A<14>{}, Pin_B<10>{}, Pin_C<7>{});

这太棒了,因为我可以理解,编译器也理解它。例如,如果我更改引脚的顺序

auto my_ic = ic(Pin_A<14>{}, Pin_C<10>{}, Pin_B<7>{});

它不会编译。

但我想知道是否有更简单的方法来实现同样的事情。你知道更好的方法吗?

您可能直接有类似以下内容:

template <typename, typename, typename> struct IC;
template<int a, int b, int c>
struct IC<Pin_A<a>, Pin_B<b>, Pin_C<c>>
{
// ...
};