【发布时间】:2019-09-16 13:35:34
【问题描述】:
我在我的 .h 文件中声明了以下模板类
enum class Hal_uart_id
{
Uart = 0,
Usart0,
Usart1,
Usart2,
Usart3,
UsbUart,
};
template <class T>
class HalUART
{
public:
HalUART(Hal_uart_id uart_id);
private:
Hal_uart_id _uart_id;
T* _p_uart;
}
在我的 .cpp 文件中,我按如下方式实现类构造函数:
#include "hal_uart_common.h"
#include "Arduino.h"
template <class T>
HalUART<T>::HalUART(Hal_uart_id id)
{
_uart_id = id;
switch (_uart_id)
{
case Hal_uart_id::Uart:
_p_uart = &Serial;
break;
case Hal_uart_id::UsbUart:
_p_uart = &SerialUSB;
break;
case Hal_uart_id::Usart0:
_p_uart = &Serial1;
break;
case Hal_uart_id::Usart1:
_p_uart = &Serial2;
break;
case Hal_uart_id::Usart3:
_p_uart = &Serial3;
break;
default:
break;
}
}
在 .cpp 文件的末尾,我使用 USARTClass 类实例化模板类
template class HalUART<USARTClass>;
我收到以下编译错误,我不明白为什么或如何解决它:
src/hal/uart/hal_uart_sam3x.cpp: In instantiation of 'HalUART<T>::HalUART(Hal_uart_id) [with T = USARTClass]':
src/hal/uart/hal_uart_sam3x.cpp:58:16: required from here
src/hal/uart/hal_uart_sam3x.cpp:23:21: error: invalid conversion from 'UARTClass*' to 'USARTClass*' [-fpermissive]
_p_uart = &Serial;
~~~~~~~~^~~~~~~~~
src/hal/uart/hal_uart_sam3x.cpp:26:21: error: cannot convert 'Serial_*' to 'USARTClass*' in assignment
_p_uart = &SerialUSB;
~~~~~~~~^~~~~~~~~~~~
*** [.pio/build/due/src/hal/uart/hal_uart_sam3x.cpp.o] Error 1
这些对象在 Arduino 核心中定义
UARTClass Serial;
USARTClass Serial1;
USARTClass Serial2;
USARTClass Serial3;
Serial_ SerialUSB;
有关 UART/USART 类和对象定义,请参阅: https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/UARTClass.h https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/UARTClass.cpp
https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/USARTClass.h https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/USARTClass.cpp
https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/USB/USBAPI.h https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/USB/CDC.cpp
【问题讨论】:
-
您很可能混合了继承对象和继承对象的类型,因此您的指针分配是非法的。但是,为了确保我需要在构造函数中使用 Serial、SerialUSB 和其他定义以及 USARTClass。
-
请提供minimal reproducible example。您没有提供
Serial的定义,所以我们无法确定它是什么。 -
@L.F.:与 cpp 中的模板无关,因为 OP 显式实例化了该类。
-
@Jarod42 OP 可能在另一个翻译单元中使用了这个模板类,对吧?