如何将模板化类实例作为模板参数传递给另一个模板?

How do you pass a templated class instance as a template parameter to another template?

本文关键字:参数传递 另一个 实例      更新时间:2023-10-16

我有一个类模板,我想将其实例作为模板参数传递给另一个类模板。如:

typedef Pin<(uint16_t)&PORTB,0> B0;
typedef Pin<(uint16_t)&PORTB,1> B1;

然后我想像这样传递它们:

Indicator<B0,B1> Ind1;

我正在使用的引脚类模板:

template <uint16_t tPort, uint8_t tBit>
class Pin
{
public:
static constexpr uint16_t Port = tPort;
static constexpr uint16_t DDR = tPort-1;
static constexpr uint16_t PIn = tPort-2;
static constexpr uint8_t Bit = tBit;
static constexpr void  Toggle() 
{
*reinterpret_cast<uint16_t*>(Port) ^= (1<<Bit);
}
static constexpr void PullHigh() 
{
*reinterpret_cast<uint16_t*>(Port) |= (1<<Bit);
}
static constexpr void PullLow() 
{
*reinterpret_cast<uint16_t*>(Port) &= ~(1<<Bit);
}
static constexpr void SetOutput() 
{
*reinterpret_cast<uint16_t*>(DDR) &= ~(1<<Bit);
}
static constexpr void SetInput() 
{
*reinterpret_cast<uint16_t*>(DDR) |= (1<<Bit);
}
static constexpr void SetHighImpedance() 
{
*reinterpret_cast<uint16_t*>(Port) &= ~(1<<Bit);
*reinterpret_cast<uint16_t*>(DDR) &= ~(1<<Bit);
}
static constexpr bool Read() 
{
return (*reinterpret_cast<uint16_t*>(PIn) & (1<<Bit));
}
};

我已经能够将它们传递给模板函数。我认为模板模板参数可能是答案。但是一直无法让它工作...

非类型模板参数不限于整数。您似乎传递了uint16_t只是将其重新解释为指针。相反,您可以将指针本身作为模板参数传递。

另请注意,constexpr上下文中不允许reinterpret_cast

在编译时传递指针如下所示:

template <uint16_t* tPort, uint8_t tBit>
class Pin
{
// ...
};

它将像这样使用:

using B1 = Pin<&PORTB, 1>;

假设您要编写Indicator模板类,它将如下所示:

template<typename P1, typename P2>
struct Indicator {
// ...
};

如果您担心强制P1P2成为引脚,可以通过创建类型特征并对其进行断言来完成:

// Base case
template<typename>
struct is_pin : std::false_type {};
// Case where the first parameter is a pin
template <uint16_t* tPort, uint8_t tBit>
struct is_pin<Pin<tPort, tBit>> : std::true_type {};

然后,使用您的断言:

template<typename P1, typename P2>
struct Indicator {
static_assert(is_pin<P1>::value && is_pin<P2>::value, "P1 and P2 must be pins");
// ...
};

然后,要使函数接收Indicator,您可以执行以下操作:

// Pass type only, and use static members
template<typename IndicatorType>
void do_stuff() {
IndicatorType::stuff();
}
// Pass an instance of the class
template<typename IndicatorType>
void do_stuff(IndicatorType indicator) {
indicator.stuff();
}

这些函数的调用方式如下:

// Passing only the type
do_stuff<Indicator<B1, A1>>();
// Passing an instance
Indicator<B1, A1> indicator;
do_stuff(indicator);

这一次我不会担心IndicatorType不是一个指标。任何充当指示符的类都将被接受,如果不能以与指标相同的方式使用,则会发生编译时错误。这将使指标的执行方式具有更大的灵活性。

另外,我建议您阅读更多或更深入的有关C++模板的教程。有时被忽视,它是C++最重要和最复杂的特征之一。