Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I was able to come up with a solution that works in all major compilers. Sadly, there is a preprocessor check for MSVC because it complains about the solution for other compilers. The main difference is that MSVC does not accept function pointers inside sizeof() and conversely, GCC does not seem to accept <code>(&amp;C::resize == 0)</code> in the check. Clang happily accepts both.</p> <pre><code>#include &lt;iostream&gt; class Base { public: void resize(int, int, int) { } }; class Derived : public Base { }; class Unrelated { }; template&lt;typename T&gt; class has_resize_method { struct Yes { char unused[1]; }; struct No { char unused[2]; }; #ifdef _MSC_VER template &lt;class C&gt; static Yes test(char (*)[(&amp;C::resize == 0) + 1]); #else template &lt;class C&gt; static Yes test(char (*)[sizeof(&amp;C::resize) + 1]); #endif template&lt;class C&gt; static No test(...); public: static const bool value = (sizeof(test&lt;T&gt;(0)) == sizeof(Yes)); }; int main() { std::cout &lt;&lt; (has_resize_method&lt;Base&gt;::value ? "Base has method resize" : "Base has NO method resize") &lt;&lt; std::endl; std::cout &lt;&lt; (has_resize_method&lt;Derived&gt;::value ? "Derived has method resize" : "Derived has NO method resize") &lt;&lt; std::endl; std::cout &lt;&lt; (has_resize_method&lt;Unrelated&gt;::value ? "Unrelated has method resize" : "Unrelated has NO method resize") &lt;&lt; std::endl; return 0; } </code></pre> <p>Output:</p> <pre><code>Base has method resize Derived has method resize Unrelated has NO method resize </code></pre> <p>Tested on GCC 4.5.3, GCC 4.3.4, Clang 3.0, Visual C++ 2008 and Visual C++ 2010. I don't have access to Visual C++ 2005 but I think it will work there, too. It also compiles on <a href="http://www.comeaucomputing.com/tryitout/" rel="nofollow">Comeau Online</a> but I cannot guarantee it produces a correct output there.</p> <p>Works with both final and __sealed classes.</p> <p>Note though that it checks not only for member functions but for member pointers in general. You might want to add additional checks such as <code>boost::is_member_function_pointer</code> if this behavior is unwanted. Similarly, you might want to add checks for number of arguments/argument types/result types - again, boost will be very helpful here, esp. <a href="http://www.boost.org/doc/libs/1_46_1/libs/function_types/doc/html/boost_functiontypes/reference/decomposition.html" rel="nofollow">boost type decomposition</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload