抽象基底クラスの契約
Coddyの「R開発者のためのC++」コースのレッスン 40/48。
R S3には宣言されたインターフェースがありません。ジェネリックは、対応するメソッドを持つクラスのオブジェクトであれば何でも受け入れます。また、メソッドが見つからないことが判明するのは、呼び出しが実行されたときだけです。C++の抽象基底クラスによるポリモーフィズムには、明示的な関係が必要です。C++の抽象基底クラスでは、純粋仮想関数と明示的な継承を使用します。メソッド名が一致するだけでは、この関係は成立しません。
R
render <- function(r, text) UseMethod("render")
render.plain <- function(r, text) text
render.bracketed <- function(r, text) paste0("[", text, "]")
renderers <- list(structure(list(), class = "plain"),
structure(list(), class = "bracketed"))
for (r in renderers) {
writeLines(render(r, "hi"))
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Shape{virtual ~Shape()=default;virtual std::string name()const=0;};struct Square:Shape{std::string name()const override{return "square";}};
int main(){
Square x;const Shape& s=x;std::cout<<s.name()<<"\n";
}
各プログラムを個別にトレースしてください。これらの例では、課題とは異なる操作やデータを使って概念を示しています。ソースとターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力:テキスト1行。Channelは純粋仮想関数sendと仮想デストラクターを宣言します。Plainはテキストを返し、Taggedはタグ、コロン、テキストを連結して返します。ドライバーは、タグがlogのTaggedに続けてPlainを出力します。
編集可能なモジュール:Channel.cpp、Channel.hpp、Plain.cpp、Plain.hpp、Tagged.cpp、Tagged.hpp。各必須型には、それぞれ名前付きのヘッダーと実装ファイルがあります。すべての公開シグネチャを保持してください。ロックされたmain.cppは標準入力を読み取り、APIを直接呼び出します。また、記載されている場合は公開APIの動作も独立して確認します。API内で出力するのではなく、戻り値を返してください。整数の入力と結果は符号付きintの範囲内です。特に指定がない限り、テキストはASCIIです。
自分で試してみよう
#include "Channel.hpp"
#include "Plain.hpp"
#include "Tagged.hpp"
#include <iostream>
int main(){
{Plain p;Tagged t("warn");const Channel& a=p;const Channel& b=t;if(a.send("probe")!="probe"||b.send("other")!="warn:other")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
Plain a;Tagged b("log");std::string s=rows.empty()?"":rows[0];for(const Channel* p:std::vector<const Channel*>{&a,&b})std::cout<<p->send(s)<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
R開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ