创建一个具有两个可能继承的类
creating a class with two possible inheritances
我有一个名为 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) {
^~~~~
这是我对你想要什么的猜测:
测试(也在 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.
在头文件中找出我需要的语法:
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;
}
实现函数中的类型很讨厌,但它编译...如果有人建议让它看起来更好,那将是有帮助的。
相关文章:
- 两个继承类如何调用彼此的方法?
- 从两个不同类继承的非虚拟基类的访问成员
- 创建一个具有两个可能继承的类
- 无法调用通过两个类继承的虚拟方法
- 从两个类继承的空类,一个是模板
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 从同一类的两个不同模板副本继承时重载
- 从两个无法改变的标头继承
- 从 C++ 中的两个类继承并插入到列表中
- 通过调用两个参数化的父类构造函数来构造继承的类
- 继承-在两个不同的类中使用相同的方法名
- 两个不同的继承指针地址是如何相等的
- 具有不同签名的两个函数的继承隐藏了非虚函数
- 从两个抽象类继承
- 基于可变参数模板的两个交互类的多重继承
- 从两个类继承的类,具有相同的函数原型,彼此冲突
- 从两个模板参数多重继承的奇怪之处
- 防止一个类的派生类对两个类进行多重继承
- 当继承基模板类并将两个类文件放在单独的头文件中时,为什么会出现重定义错误
- 如何在编译时推导出两个类型共有的继承树的根(如果存在)