On Dec 11, 5:48 pm, Belebele <beluc...@gmail.comwrote:
I don't see how this can be "simple to implement",
except by using function pointers, which is not
particularily simple, safe or fun to play with.
See Listing 1 on http://www.ddj.com/cpp/184401848. Yep,
function pointers to the rescue. Nothing really too
extraordinary.
I copy the listing (with some corrections) for the sake of the
discussion:
# include <iostream>
struct AbcFuBar
{
virtual ~AbcFuBar()
{
}
virtual void FuBar() = 0;
};
struct BaseFuBar : public AbcFuBar
{
void FuBar()
{
std::cout << "BaseFuBar";
}
};
struct DerivedFuBar : public BaseFuBar
{
void FuBar()
{
std::cout << "DerivedFuBar";
}
};
int main()
{
DerivedFuBar d;
BaseFuBar& b = d;
AbcFuBar& a = b;
a.FuBar(); // output DerivedFuBar
}
This example does not correspond to your original post. It
only demonstrates the use of inheritance and virtual
functions.
The method template requirement is what puzzles me.
I would prefer not having to force the Wrapped objects
to derive (in my case artificially) from a base class.
Basically, you need templates if you don't have a base class.
Otherwise, what will be the type of the member object of your
"Interface" class?
class wrapper
{
public:
template <class T>
wrapper(T& t)
: t_(t)
{
}
private
??? t_;
};
Note that you cannot replace ??? by T, since it only exists in
the constructor. To do this, make wrapper a template:
template <class T>
class wrapper
{
public:
wrapper(T& t)
: t_(t)
{
}
private:
T t_;
};
in which case the constructor does not need to be templated
anymore (unless it should accept things that are not Ts).
Now, if you want to call member functions on the wrapped
oject, you need to know the function names along with the type
and numbers of parameters they take.
template <class T>
class wrapper
{
public:
wrapper(T& t)
: t_(t)
{
}
void f(int i)
{
t_.f(i);
}
private:
T t_;
};
class bar
{
public:
void f(int i)
{
}
};
int main()
{
bar b;
wrapper<barw(b);
w.f(0);
}
To remove the "hardcoded" type information in f(), you can use
templates:
template <class T>
class wrapper
{
public:
wrapper(T& t)
: t_(t)
{
}
template <class P1>
void f(P1 p1)
{
t_.f(p1);
}
private:
T t_;
};
--
Jonathan Mcdougall