我正在爲不同類型的協議消息編寫接口類。我不能重新編寫基本協議代碼,以便爲每個協議提供一個通用接口,我正在爲每個特定協議創建一個具有包裝類的通用接口的基類。具有不同返回類型的虛函數
因此,每個包裝類將有一個共同的接口,然後在我的代碼來處理協議消息,我可以使用多態即
message* msg = new protocol_a_msg(a_msg);
然後,我可以使用的功能與消息*參數來處理等,這是大。
但是,最終我需要獲取底層協議消息。所以我想寫一個虛擬函數來獲取底層消息。即在基本消息類別中:
<type> get_msg() = 0;
但是麻煩是會變化的。這是否意味着我不能擁有一個虛擬函數,因爲返回類型有所不同?
如果我不能這樣做,我需要轉換爲特定的協議包裝類型並使用特定的功能。哪個可行,但我想知道什麼是最好的方法。
這是到目前爲止我的代碼:
#include <iostream>
class message {
public:
enum msg_type { PROTOCOLTYPE, BINARYTYPE, UNKNOWNTYPE };
message(msg_type type = PROTOCOLTYPE) : type_(type) {}
void set_type(msg_type type) { type_ = type; }
msg_type get_type() const { return type_; }
msg_type type_;
virtual ~message() {}
// Can I make this a generic get underlying data virtual function?
// virtual underlying_msg get_msg() const { return <underlying_msg>; }
//may also need a set_msg(msg) - or can initialise protocol msg in ctor
};
//this is existing protocol code which I cannot change
class protocol_a {
public:
enum a_type { SMALL, MEDIUM, LARGE };
protocol_a(a_type a) : atype_(a) { }
const char* get_data() {
static const char* const names[] = { "SMALL", "MEDIUM", "LARGE" };
return names[atype_];
}
protected:
a_type atype_;
};
class protocol_a_msg : public message {
public:
protocol_a_msg(protocol_a * a) : proto_(a) {}
protocol_a* get_msg() const { return proto_; }
protocol_a* proto_;
};
int main() {
protocol_a a_msg(protocol_a::SMALL);
protocol_a_msg* pa_msg = new protocol_a_msg(&a_msg);
//retrieve underlying protocol_a msg
protocol_a* a = pa_msg->get_msg();
const char* s = a->get_data();
std::cout << "protocol_a data=" << s << std::endl;
delete [] pa_msg;
return 0;
}
這是模板是。 –
虛擬方法不能模板化 – nouney
@nouney:你從哪裏得到的? – slaphappy