我有一個類(base
),它有許多繼承者(derived_i
)和一些其他類型(other
)。我想在某些類處理程序中使用模板方法(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
成爲一個類的繼承者。 =(
它不會解決你的問題,但這裏有一個錯字:'base_specific_method()'和'base_speciffic_method()'。 – songyuanyao
[將派生類傳遞給專用於基類的模板函數](http://stackoverflow.com/questions/27988024/passing-a-derived-class-to-a-template-function-specialized-with -base-class) – PcAF
@songyuanyao是的,謝謝! – shved