我有一个非模板类(Uart),想要创建模板构造函数。它需要采用另一个模板类对象(SafeQueue)。然后这个构造函数将调用类中定义的另一个模板函数。
下面给出了类签名;
class UartCommunication
{
public:
UartCommunication(const char *port, speed_t baudRate);
template <typename SendStruct, typename ReceiveStruct, typename SendQueue = SafeQueue<SendStruct>, typename ReceiveQueue = SafeQueue<ReceiveStruct>>
UartCommunication(const char* port, speed_t baudRate,
SendQueue& sendQueue, ReceiveQueue& receiveQueue,
int pollingTime, bool sendIfReceived)
{
port_ = port;
baudRate_ = baudRate;
serial_fd_ = open(port_, O_RDWR | O_NOCTTY | O_NDELAY);
if (serial_fd_ == -1)
{
std::cerr << "Error opening serial port" << std::endl;
// Handle error
}
std::cout << "serial_fd_:" << serial_fd_ << std::endl;
ConfigureSerialPort();
// Start a thread to receive data
receiveThread_ = std::thread(&SendAndReceiveStruct<SendStruct, ReceiveStruct>, this,
sendQueue, receiveQueue, pollingTime, sendIfReceived);
}
// SentAndReceiveStruct from UART
template <typename SendStruct, typename ReceiveStruct, typename SendQueue = SafeQueue<SendStruct>, typename ReceiveQueue = SafeQueue<ReceiveStruct>>
void SendAndReceiveStruct(SendQueue& sendQueue, ReceiveQueue& receiveQueue, int pollingTime, bool sendIfReceived)
{
///codes
}
}
///
// A threadsafe-queue.
template <class T>
class SafeQueue
{
}
我可以构建代码,而无需使用模板 const 从 Uart 类创建任何对象。实际上SendAndReceiveStruct函数与const具有相同的签名,并且可以在线程函数中调用。但是当我尝试用类似的方式创建一个Uart对象时;
UartCommunication<InputStruct, OutputStruct> pcUart("/dev/ttyUSB0", B921600, AlgoTester::safeQueueInstanceAlgoInput, AlgoTester::safeQueueInstanceAlgoOutput, 20, false);
我明白了 类“UartCommunication”可能没有模板参数列表C/C++(519) “UartCommunication”不是 templateGCC 错误。我提供了 SafeQueue 实例的模板,但是这样使用它是否含糊不清?我需要使用safequeue模板作为对象,所以我不能直接使用safequeue对象作为模板。
感谢您的帮助。
auto pcUart = UartCommunication<InputStruct, OutputStruct>("/dev/ttyUSB0", B921600, AlgoTester::safeQueueInstanceAlgoInput, AlgoTester::safeQueueInstanceAlgoOutput, 20, false);
或者
UartCommunication pcUart = UartCommunication<InputStruct, OutputStruct>("/dev/ttyUSB0", B921600, AlgoTester::safeQueueInstanceAlgoInput, AlgoTester::safeQueueInstanceAlgoOutput, 20, false);