I have a class (base
) which has many inheritors (derived_i
) and some other types (other
). I want to have a template method in some class-handler (caller
), which handles inheritors of base
in differ way, then from other types.
Here is an example code I telling about.
#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();
}
It compiled with g++ -std=c++11 test.cpp
and output is next:
each_class_has_this this is boring...
base_specific_method method called: 0
each_class_has_this this is boring...
While I'm expecting
each_class_has_this this is boring...
base_specific_method method called: 0
base_specific_method Hey! I'm interesting derived! And 10 == 10
Is there any way to change this code to make it suitable my requests?
This question seems to be a duplicate of another question, but the correct answer on it leads to the problem, I faced here.
P.S. There is no way to make base
and other
the inheritors from one class. =(