Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Metaprogramming method for "class method exists"

82 views
Skip to first unread message

gabe

unread,
May 19, 2006, 6:02:01 AM5/19/06
to
Hey there

I'm wondering if there's some way to execute code based on the
condition that a specified class has a specified member function.

I've got a class MyClass which takes as a template parameter its Base
class. the Base class follows a concept in which some methods I would
like to be optional, so I'll need to execute different version of
functions in MyClass depending on the existence of methods in Base.

Does anyone know of something like this, has code or has a
work-around/better idea?

thanks much,
Gabe


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Dan McLeran

unread,
May 20, 2006, 5:27:44 PM5/20/06
to
>I'm wondering if there's some way to execute code based on the
>condition that a specified class has a specified member function.

Boost has something that might be useful:
http://www.boost.org/doc/html/boost_typetraits/reference.html#boost_typetraits.is_member_function_pointer

You could test for the existence of a function signature, i.e. airty,
arg type, etc. and make
some compile-time decisions based on that.

Philippe Amarenco

unread,
May 23, 2006, 7:04:49 AM5/23/06
to
"gabe" <gabe....@gmail.com> writes:

> Hey there
>
> I'm wondering if there's some way to execute code based on the
> condition that a specified class has a specified member function.
>
> I've got a class MyClass which takes as a template parameter its Base
> class. the Base class follows a concept in which some methods I would
> like to be optional, so I'll need to execute different version of
> functions in MyClass depending on the existence of methods in Base.
>
> Does anyone know of something like this, has code or has a
> work-around/better idea?
>

if you are looking for a method that is of the form:

"int myclass::some_methode(int)"

then use this (SFINAE trick):


typedef char present_t;
typedef struct { char a[2]; } absent_t;

template <typename T>
struct test
{
template <typename U, int (U::*f)(int n) = &U::some_method>
struct helper{};

template <typename U>
static absent_t is_here(...);

template <typename U>
static present_t is_here(helper<U>*);

enum { ret = (sizeof(is_here<T>(0)) == sizeof(present_t)) };
};


note: it discovers if a specific class has a method but not a
hierachy:

class A {
int some_method(int);
};

class B : A {
};

test<A>::ret -> true
test<B>::ret -> false

the trick that would make this work causes GCC to segfault so i can't
test it.

--
Philippe Amarenco, aka Phix
epita 2007 - GISTR - LSE - EpX

0 new messages