我有一个名为Radio的类,我希望能够从名为Serial的类或名为Stream的类继承,具体取决于对象的创建方式。我想这可以通过以下模板来完成:
template<class InterfaceType>
class Radio : public InterfaceType
{
...
};
并创建像
这样的对象Radio<Serial> serialRadio;
Radio<Stream> streamRadio;
这是一个好主意吗?
在我的实现文件中,我定义了类中的函数,我得到的错误如下:
radio.cpp:52:6: error: ‘template<class InterfaceType> class Radio’ used without template parameters
void Radio::mavlinkReceiveByte(uint8_t data) {
^~~~~
答案 0 :(得分:0)
以下是我对你想要的猜测:
测试(也在godbolt.org)
#include <iostream>
#include <string>
// -- Data source --
class Stream {
public:
explicit Stream(int x) {}
std::string get_data() { return "tweet."; }
};
class Serial {
public:
std::string get_data() { return "chirp."; }
};
// -- Interfaces --
template<class Data_source>
class Radio {
public:
explicit Radio(Data_source&& ds) : data_source(std::move(ds)) {}
void nom();
private:
Data_source data_source;
};
template <class D>
void Radio<D>::nom() {
std::cout << data_source.get_data() << "\n";
}
template<class Data_source>
class Radio_alarm : Radio<Data_source> {
using Base = Radio<Data_source>;
public:
explicit Radio_alarm(Data_source&& ds)
: Base(std::move(ds)) {}
void nom_x10() {
for (int i = 0; i < 10; ++i) {
std::cout << "[" << i << "]: ";
Base::nom();
}
}
};
// -- Test --
int main() {
Radio stream_r(Stream(1));
Radio serial_r((Serial()));
serial_r.nom();
Radio_alarm r_alarm((Stream(1)));
r_alarm.nom_x10();
}
结果:
chirp.
[0]: tweet.
[1]: tweet.
[2]: tweet.
[3]: tweet.
[4]: tweet.
[5]: tweet.
[6]: tweet.
[7]: tweet.
[8]: tweet.
[9]: tweet.
答案 1 :(得分:0)
在头文件中找出我需要的语法:
template<class InterfaceType>
class Radio : public InterfaceType
{
public:
struct buffer
{
uint16_t len;
std::shared_ptr<uint8_t[]> buf;
};
struct channels {
uint16_t rollPWM, pitchPWM, yawPWM, throttlePWM;
};
buffer sendHeartbeat(uint8_t mode, uint8_t status);
void mavlinkReceiveByte(uint8_t data);
void mavlinkReceivePacket(uint8_t *packet);
channels getRCChannels();
private:
channels pwmInputs;
};
实现文件中的示例函数:
template<typename InterfaceType>
typename Radio<InterfaceType>::buffer Radio<InterfaceType>::sendHeartbeat(uint8_t mode, uint8_t status) {
mavlink_message_t msg;
uint16_t len;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
mavlink_msg_heartbeat_pack(SYSID, COMPID, &msg, MAV_TYPE_QUADROTOR, MAV_AUTOPILOT_GENERIC, mode, 0, status);
len = mavlink_msg_to_send_buffer(buf, &msg);
buffer sendBuffer;
sendBuffer.buf = (std::shared_ptr<uint8_t[]>)buf;
sendBuffer.len = len;
return sendBuffer;
}
实现函数中的类型是令人讨厌的,但它编译...如果有人有建议使这看起来更好,那将是有帮助的。