さまざまな種類のプロトコル メッセージのインターフェイス クラスを作成しています。基本プロトコル コードを書き直すことはできないため、各プロトコルに共通のインターフェイスを提供するために、特定のプロトコルごとにラッパー クラスを持つ共通インターフェイスを持つ基本クラスを作成しています。
したがって、各ラッパークラスには共通のインターフェースがあり、コードでプロトコルメッセージを処理するためにポリモーフィズムを使用できます。
message* msg = new protocol_a_msg(a_msg);
次に、message* パラメータを含む関数を使用して処理などを行うことができます。これは素晴らしいことです。
ただし、最終的には、基になるプロトコル メッセージを取得する必要があります。そのため、基になるメッセージを取得する仮想関数を書きたかったのです。つまり、基本メッセージ クラス:
<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;
}