Question about how to integrate different classes for uniforming the interface
Hi all!
I have some classes (say C1 and C2) belonging to an external library
which I would like with my own template class by providing a "uniform"
interface.
My template class (say C_user_base<C>) expects that the template
paramter C defines a type named "value_type", that is:
--- [snip] ---
template <typename C>
struct C_user_base
{
typedef C::value_type value_type;
}
--- [/snip] ---
I've tried the following solution (in short I use a traits class which
is specialized for each class belonging to the external lib).
It seems to work!
But I wonder if a *better* solution is possible.
--- [snip] ---
#include <iostream>
#include <typeinfo>
template <typename T1, typename T2, typename T3>
struct C1 // <-- coming from external lib
{
typedef T1 val_type;
//...
};
template <typename T1, typename T2>
struct C2 // <-- coming from external lib
{
typedef T1 t1_type;
//...
};
template <typename T>
struct MyC // <-- my own class
{
typedef T value_type;
//...
};
// Traits class for hiding detail of each C class
template <typename C>
struct C_traits
{
typedef typename C::value_type value_type;
};
template <typename T1, typename T2, typename T3>
struct C_traits< C1<T1,T2,T3> >
{
typedef typename C1<T1,T2,T3>::val_type value_type;
};
template <typename T1, typename T2>
struct C_traits< C2<T1,T2> >
{
typedef typename C2<T1,T2>::t1_type value_type;
};
template <typename C>
struct C_user_base
{
typedef typename C::value_type value_type;
};
template <typename C, template <typename> class C_T = C_traits >
struct C_user_adapter: public C_user_base< C_T<C> >
{
//typedef typename C_T::value_type value_type;
};
template <typename T>
void print_type()
{
std::cout << "Type: " << typeid(T).name() << std::endl;
}
int main()
{
print_type< C_user_base< MyC<int> >::value_type >();
print_type< C_user_adapter< C1<int,double,char> >::value_type >();
print_type< C_user_adapter< C2<double,char> >::value_type >();
return 0;
}
--- [/snip] ---
Compiled with GCC 4.3: g++ -Wall -pedantic -ansi ...
Thank you very much in advance for considering!!
Cheers,
-- Marco
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]