Re: picking a base class with a tag
On Jun 19, 7:22 pm, Cory Nelson <phro...@gmail.com> wrote:
I've got a class like this:
template<typename Tag>
struct BaseA;
template<typename Tag>
struct BaseB;
struct Derived : BaseA<Tag1>, BaseA<Tag2>, BaseB<Tag3> {};
static_casting to get at the bases is getting too verbose, I would
like to write a get() that returns a reference to the correct base
given a tag. ie:
Derived d;
BaseA<Tag1> &b = get<Tag1>(d);
But I'm drawing a blank.. any ideas?
--
[ Seehttp://www.gotw.ca/resources/clcm.htmfor info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
{ Do we really need the clc++m banner quoted?
Please remove irrelevant material from your quoting yourself. -mod }
You could try something like this (works w/ CodeBlocks and GCC):
#include <iostream>
template <int name>
struct Tag
{
static int GetName() { return name;}
};
template <class T>
struct BaseA
{
BaseA()
{}
static int HasATag() { return T::GetName();}
};
template <class T>
struct BaseB
{
BaseB()
{}
static int HasBTag() { return T::GetName();}
};
typedef Tag< 1> Tag1;
typedef Tag< 2> Tag2;
typedef Tag< 3> Tag3;
struct Derived : BaseA<Tag1>, BaseA<Tag2>, BaseB<Tag3> {};
template< template<class> class Cl, typename Ty, typename P>
inline Cl<Ty> TypeOfArg2TypeOfTemplateArg( P p, const Ty&)
{
return Cl<Ty>( p);
}
template< typename Ty>
inline BaseA<Ty> Get( Derived d)
{
return TypeOfArg2TypeOfTemplateArg<BaseA>( d, Ty());
}
int main()
{
Derived d;
BaseA< Tag1> ba1 = Get<Tag1>( d);
BaseA< Tag2> ba2 = Get<Tag2>( d);
std::cout << "ba1.HasATag " << ba1.HasATag() << std::endl;
std::cout << "ba2.HasATag " << ba2.HasATag() << std::endl;
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]