私は、多くの継承者(derived_i
)といくつかの他の型(other
)を持つクラス(base
)を持っています。いくつかのクラスハンドラ(caller
)にテンプレートメソッドを持たせたいと考えています。これは、異なる方法でbase
の継承者を処理し、次に他の型から継承します。継承者などを相殺するようにテンプレート関数を作成する
ここに私が言っているコード例があります。
#include <iostream>
using namespace std;
template <typename T>
class base {
public:
base (T val = T())
: m_val(val)
{}
base (const base &other)
: base(other.m_val)
{}
virtual void base_specific_method()
{
cout << __func__ << " method called: " << m_val << endl;
}
void each_class_has_this() {
cout << __func__ << " this is boring..." << endl;
}
T m_val;
};
class other {
public:
void each_class_has_this() {
cout << __func__ <<" this is boring..." << endl;
}
};
class derived_i : public base <int>
{
public:
derived_i() : base <int> (10)
{}
virtual void base_specific_method()
{
cout << __func__ <<" Hey! I'm interesting derived! And 10 == " << m_val << endl;
}
};
template <typename T>
class caller {
public:
caller (T val = T())
: m_val(val)
{}
void call() {
p_call(m_val);
}
private:
template <typename T1> void p_call (T1 &val)
{
val.each_class_has_this();
}
template <typename T1> void p_call (base<T1> &val)
{
val.base_specific_method();
}
private:
T m_val;
};
int main()
{
caller<other> c1;
caller<base<double> > c2;
caller<derived_i > c3;
c1.call();
c2.call();
c3.call();
}
それはg++ -std=c++11 test.cpp
でコンパイルされ、出力は次です:
each_class_has_this this is boring...
base_specific_method method called: 0
each_class_has_this this is boring...
私は
each_class_has_this this is boring...
base_specific_method method called: 0
base_specific_method Hey! I'm interesting derived! And 10 == 10
を期待していますが、それに適した私の要求にするために、このコードを変更する方法はありますか?
この質問はanother questionと重複しているようですが、それに対する正解は問題につながります。私はここで直面しました。
P.S.あるクラスから継承者をbase
とother
にする方法はありません。 =(
これはあなたの問題を解決することはできませんが、ここでは、typo: 'base_specific_method()'と 'base_speciffic_method()'です。 – songyuanyao
[派生クラスを基本クラスに特化したテンプレート関数に渡す]の可能な複製(http://stackoverflow.com/questions/27988024/passing-a-derived-class-to-a-template-function-specialized-withベースクラス) – PcAF
@songyuanyaoうん、ありがとう! – shved