私の実際の例はかなり大きいので、私は単純化したものを使用します。ポインタ、値、スマートポインタのためのC++テンプレートの統一
struct Rectangle {
int width;
int height;
int computeArea() {
return width * height;
}
}
そして例えば、そのタイプを消費し、別の種類::私は長方形のデータ型があると今
struct TwoRectangles {
Rectangle a;
Rectangle b;
int computeArea() {
// Ignore case where they overlap for the sake of argument!
return a.computeArea() + b.computeArea();
}
};
を、私はのユーザーに所有権の制約を入れたくありませんTwoRectangles
ので、私はそれのテンプレートしたいと思います:
template<typename T>
struct TwoRectangles {
T a;
T b;
int computeArea() {
// Ignore case where they overlap for the sake of argument!
return a.computeArea() + b.computeArea();
}
};
用途:
TwoRectangles<Rectangle> x;
TwoRectangles<Rectangle*> y;
TwoRectangles<std::shared_ptr<Rectangle>> z;
// etc...
問題は、発信者は、ポインタを使用したい場合は、関数の本体が異なるということです。
template<typename T>
struct TwoRectangles {
T a;
T b;
int computeArea() {
assert(a && b);
return a->computeArea() + b->computeArea();
}
};
コードのmaxiumum量があるように私のテンプレート機能を統合する最良の方法は何ですかポインタ、値、スマートポインタのために再利用されますか?それはあなたがそれらの式の両方が有効であるのためのタイプがあるでしょうそうだ
template<typename T>
struct TwoRectangles {
T a;
T b;
int computeArea() {
return areaOf(a) + areaOf(b);
}
private:
template <class U>
auto areaOf(U& v) -> decltype(v->computeArea()) {
return v->computeArea();
}
template <class U>
auto areaOf(U& v) -> decltype(v.computeArea()) {
return v.computeArea();
}
};
:
あなたは適用できないものを除外するためにSFINAEで過負荷の束を書くことができます。または、必要なものだけを処理するようにデザインを変更し、実際に必要になるまで必要と思われるものを除外することができます。 –
' - >'のみを使用してください。カスタムポインタのようなオブジェクトにポインタ以外の値をラップします。 –
あなたは標準のライブラリを何かすることができ、追加のテンプレートタイプを与えることができます。これは "Tをどうやって取得するか"を知っていて、 'computeArea'を呼び出していることです。それとも、あまりにもそれをエンジニアリングしないでください。 :) – GManNickG