Re: Detecting if a class has a particular method at compile time
* Mayuresh:
There are two existing interfaces -
//interface1.H
class Interface1
{
public :
static void foo();
};
//interface2.H
class Interface2
{
public :
static void bar();
};
Now, I want to write a class template that can be instantiated with
any of the above classes :
template<class T>
class User
{
public:
static void f()
{
//if T::foo() exists then invoke it.
//else if T::bar() exists then invoke it.
//else do some custom logic here....
}
};
It is required that User can be instantiated with either Interface1 or
Interface2 without compilation problems
How can I express this in C++ ? (I can do it by making two explicit
specializations for Interface1 and Interface2, but in my real case, I
have a lot of these Interfaces, so I would like to avoid explicitly
specializing for all cases)
Why don't you specialize just the part that differs, or parts that differ.
E.g.
<code>
#include <iostream>
void say( char const s[] ) { std::cout << s << std::endl; }
class Interface1
{
public :
void moo() { say( "moo" ); }
static void foo() { say( "foo" ); }
};
class Interface2
{
public :
void mar() { say( "mar" ); }
static void bar() { say( "bar" ); }
};
template< typename T >
struct FooBar_moofoo
{
static void m( T& o ) { o.moo(); }
static void f() { T::foo(); }
};
template< typename T >
struct FooBar_marbar
{
static void m( T& o ) { o.mar(); }
static void f() { T::bar(); }
};
template< class T > struct FooBarAdaptor;
template<> struct FooBarAdaptor<Interface1>: FooBar_moofoo<Interface1> {};
template<> struct FooBarAdaptor<Interface2>: FooBar_marbar<Interface2> {};
template< class T >
class User
{
public:
static void f()
{
T o;
FooBarAdaptor<T>::f();
FooBarAdaptor<T>::m( o );
}
};
int main()
{
User<Interface1>::f();
User<Interface2>::f();
}
</code>
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]