has_interface trait
Now say I build an interface like this:
class IInterface
{
public:
virtual void foo() = 0;
virtual ~IInterface() {};
};
template<class T>
class Box : public virtual IInterface
{
T * x;
public:
Box()
{
}
Box(T * x)
{
this->x = x;
}
virtual void foo()
{
x->foo();
}
};
class Interface
{
private:
IInterface * x;
public:
template<class T>
Interface(T * x)
{
this->x = new Box<T>(x);
}
IInterface & operator*()
{
return *x;
}
IInterface * operator-> ()
{
return x;
}
};
Now say I have two classes like this:
class A
{
public:
void foo()
{
printf("foo is called\n");
}
};
class B
{
};
If I do this:
A a;
B b;
Interface interface1 = &a; //OK Compiles
Interface interface2 = &b;//Throws compile error because b does not
have a member named foo
So i would like to create a trait to query whether i can create an
interface from B or not, something like this:
bool aHas = has_interface<A>::value; //True
bool bHas = has_interface<B>::value; //False
Ultimately, I would like to use this for function overloading,
something like this:
template <class T>
typename enable_if<has_interface<T> >::type
process(cons T& x)
{
//Optimize using this interface
}
template <class T>
void process(cons T& x)
{
//The generic code when this interface doesnt exist
}
I though maybe i could use SFINAE to do this, but I cant figure out a
way to deduce this. Perhaps there is another way to do this. Basically
if it throws a compiler error on constructing the interface, i want it
to return a false value. Does any have any ideas?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]