From f517cfb19acf4a44f30d013a054bc73264f14ec7 Mon Sep 17 00:00:00 2001 From: Ichthyostega Date: Sat, 2 Jan 2010 06:26:56 +0100 Subject: [PATCH] Yess we can! Invented a statical duck-detector! --- src/tool/try.cpp | 89 ++++++++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 40 deletions(-) diff --git a/src/tool/try.cpp b/src/tool/try.cpp index 412772c84..af6b66ae1 100644 --- a/src/tool/try.cpp +++ b/src/tool/try.cpp @@ -14,6 +14,7 @@ // 10/8 - abusing the STL containers to hold noncopyable values // 6/09 - investigating how to build a mixin template providing an operator bool() // 12/9 - tracking down a strange "warning: type qualifiers ignored on function return type" +// 1/10 - can we determine at compile time the presence of a certain function (for duck-typing)? //#include @@ -21,7 +22,6 @@ //#include "include/logging.h" //#include "include/nobugcfg.h" -#include #include //#include @@ -30,47 +30,59 @@ #include -//using std::tr1::bind; -using std::tr1::placeholders::_1; - //using std::rand; using std::string; using std::cout; +using std::endl; - - template - inline bool - eat_all (SEQ& coll, Oper predicate) +struct A { - typename SEQ::const_iterator e = coll.end(); - typename SEQ::const_iterator i = coll.begin(); - - for ( ; i!=e; ++i ) - if (!predicate(*i)) - return false; - - return true; - } - - template < typename CON, typename FUN - , typename P1 - , typename P2 - > - inline bool - eat_all (CON& elements, FUN function, P1 bind1, P2 bind2) + int& funA (); + }; + +struct B { - return eat_all (elements, std::tr1::bind (function, bind1, bind2)); - } + void funA(); + }; + + + typedef char Yes_t; + struct No_t { char padding[8]; }; + + + template + class Detector1 + { + template + struct Probe + { }; + + template + static Yes_t check(Probe*); + template + static No_t check(...); + + public: + static const bool value = (sizeof(Yes_t)==sizeof(check(0))); + }; - - bool - plainFunc (int i, int j) - { - cout <<':'<< i+j; - return i+j; - } + template + class Detector2 + { + template + struct Probe + { }; + + template + static Yes_t check(Probe*); + template + static No_t check(...); + + public: + static const bool value = (sizeof(Yes_t)==sizeof(check(0))); + }; int @@ -79,14 +91,11 @@ main (int, char**) // NOBUG_INIT; - typedef std::vector VecI; + cout << "Detector1 = " << Detector1::value << endl; + cout << "Detector1 = " << Detector1::value << endl; - uint count = 4; - VecI numberz; - while (count) - numberz.push_back(count--); - - eat_all (numberz, plainFunc, 10, _1 ); + cout << "Detector2 = " << Detector2::value << endl; + cout << "Detector2 = " << Detector2::value << endl; cout << "\n.gulp.\n";