我想把一个芯片(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是什么意思呢?我不能读这段代码,我想读我的代码。当然,我可以使用宏或常量表达式来避免魔术数字,所以我可以读取代码,但编译器不能。我希望我的编译器在a出错时通知我。
为了实现这一点,我编写了以下代码:
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>{});它不会编译。
但我想知道是否有更简单的方法来实现同样的事情。你知道更好的方法吗?
发布于 2019-07-10 01:39:38
您可能会直接拥有类似以下内容:
template <typename, typename, typename> struct IC;
template<int a, int b, int c>
struct IC<Pin_A<a>, Pin_B<b>, Pin_C<c>>
{
// ...
};https://stackoverflow.com/questions/56957776
复制相似问题