Message from discussion
Detecting a specific member function is defined
Path: archiver1.google.com!news1.google.com!newsfeed.stanford.edu!logbridge.uoregon.edu!arclight.uoregon.edu!wn13feed!wn12feed!worldnet.att.net!204.127.198.203!attbi_feed3!attbi.com!sccrnsc03.POSTED!not-for-mail
From: "Paul Mensonides" <leavi...@attbi.com>
Newsgroups: comp.lang.c++
References: <zhcba.221093$Zr%.218124@news01.bloor.is.net.cable.rogers.com> <1047353003.166417@athprx02> <b4joii$dnn@dispatch.concentric.net> <1047357891.884742@athprx02> <b4jqoi$dnj@dispatch.concentric.net> <1047368240.786458@athprx02>
Subject: Re: Detecting a specific member function is defined
Lines: 64
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1106
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106
Message-ID: <%Ugba.36183$eG2.7274@sccrnsc03>
NNTP-Posting-Host: 12.229.114.119
X-Complaints-To: abuse@attbi.com
X-Trace: sccrnsc03 1047370427 12.229.114.119 (Tue, 11 Mar 2003 08:13:47 GMT)
NNTP-Posting-Date: Tue, 11 Mar 2003 08:13:47 GMT
Organization: AT&T Broadband
Date: Tue, 11 Mar 2003 08:13:47 GMT
Ioannis Vranos wrote:
> "Phlip" <phlip...@yahoo.com> wrote in message
> news:b4jqoi$dnj@dispatch.concentric.net...
>>
>> Brian is not writing a Swap function.
>>
>> He wants a template that expands one way if its argument has a given
>> method, and another way if it does not. I honestly can't tell if you
>> read the same post as I.
>>
>> There probably is no way to do what he wants without passing some
>> kind of extra template into the main template. So, if he needed to
>> Foo instead of Swap, he'd write one of:
>>
>> Foo<MyAclass, policyWithMethod>();
>> Foo<MyBclass, policyWithoutMethod>();
>>
>> Now the question becomes this: How do you make the template
>> automatically select one or the other policy? The answer is you
>> can't.
Yes, you can:
#include <iostream>
template<class T> struct has_member_Swap;
template<class R, class C> class has_member_Swap<R C::*> {
private:
template<R C::*> struct helper;
template<class T> static char check(helper<&T::Swap>*);
template<class T> static char (& check(...))[2];
public:
enum { value = sizeof(check<C>(0)) == 1 };
};
struct A { };
struct B {
void Swap(B&) throw();
};
int main() {
std::cout
<< has_member_Swap<void (A::*)(A&) throw()>::value << '\n';
<< has_member_Swap<void (B::*)(B&) throw()>::value << &std::endl;
return 0;
}
Deduction by SFINAE. Non-class types can be excluded via:
template<class T> class is_class {
private:
template<class U> static char check(int U::*);
template<class U> static char (& check(...))[2];
public:
enum { value = sizeof(check<T>(0)) == 1 };
};
Regards,
Paul Mensonides