3

Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?

This is very similar to my earlier question. I want to check whether a template argument contains a member function or not.

I tried this code similar to that in the accepted answer in my previous question.

struct A
{
   int member_func();
};

struct B
{
};

template<typename T>
struct has_member_func
{
   template<typename C> static char func(???); //what should I put in place of '???'
   template<typename C> static int func(...);

   enum{val = sizeof(func<T>(0)) == 1};
};

int main()
{
    std::cout<< has_member_func<B>::val; //should output 0
    std::cout<< has_member_func<A>::val; //should output 1
}

But I have no idea what should I put in place of ??? to make it work. I am new to SFINAE concept.

Community
  • 1
  • 1
NEWBIE
  • 31
  • 2
  • Use something similar to HAS_MEM_FUNC which Johannes posted in that thread. I've used that code before and it works fine. – asdfjklqwer Dec 04 '10 at 14:18
  • icecrime Thanks for pointing out that this is a duplicate. However the accepted answer uses non-standard typeof operator. Can you suggest an alternative? According to MSalter's comment static char func(char[sizeof(&C::helloworld)]) should work? – NEWBIE Dec 04 '10 at 14:19
  • @NEWBIE: see Johannes answer, it's much better – icecrime Dec 04 '10 at 14:20
  • 1
    icecrime sorry but his solution is too convoluted. can you suggest something similar to the accepted solution in the original link? – NEWBIE Dec 04 '10 at 14:24
  • @NEWBIE : Check out @FireAphis's answer. It is much simpler than Johannes's answer. :) – Prasoon Saurav Dec 04 '10 at 14:39
  • @Prasoon the changes he made introduce two problems: `TypeHasToString` may fail to compile with non-class types (it won't use SFINAE when an error occurs inside `ToString<>`), and it will fail if `sizeof(char) == sizeof(long)`. I will change my answer to use typedefs so it's more readable, though. – Johannes Schaub - litb Dec 05 '10 at 06:00
  • @NEWBIE, this *is* a complicated topic for which there most probably isn't an easy solution. If this stuff is too convoluted for you, maybe that's a sign you shouldn't use it, but trying to solve the problem another way. – Johannes Schaub - litb Dec 05 '10 at 06:16

1 Answers1

1

Little modification of MSalters' idea from Is it possible to write a C++ template to check for a functions existence? :

template<typename T>
class has_member_func
{
        typedef char no;
        typedef char yes[2];
        template<class C> static yes& test(char (*)[sizeof(&C::member_func)]);
        template<class C> static no& test(...);
public:
        enum{value = sizeof(test<T>(0)) == sizeof(yes&)};
};
Community
  • 1
  • 1
Pawel Zubrycki
  • 2,703
  • 17
  • 26
  • I get this error with GCC 4.2.1: `In instantiation of ‘has_member_func’:` `error: array bound is not an integer constant` – nilton Jun 27 '11 at 05:16