Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>joshperry's answer is very clever and elegant, but (as it is stated below the post) it doesn't check the signature of foo() properly and doesn't work with fundamental types (like int): it causes a compiler error. I will propose a technique that handles inherited members correctly and also checks the signature of the member function. Instead of going into details I will give you two exampes and hope that the code will speak for itself.</p> <h2>Example1:</h2> <p>We are checking for a member with the following signature: <code>T::const_iterator begin() const</code></p> <pre><code>template&lt;class T&gt; struct has_const_begin { typedef char (&amp;Yes)[1]; typedef char (&amp;No)[2]; template&lt;class U&gt; static Yes test(U const * data, typename std::enable_if&lt;std::is_same&lt; typename U::const_iterator, decltype(data-&gt;begin()) &gt;::value&gt;::type * = 0); static No test(...); static const bool value = sizeof(Yes) == sizeof(has_const_begin::test((typename std::remove_reference&lt;T&gt;::type*)0)); }; </code></pre> <p>Please notice that it even checks the constness of the method, and works with primitive types, as well. (I mean <code>has_const_begin&lt;int&gt;::value</code> is false and doesn't cause a compile-time error.) </p> <h2>Example 2</h2> <p>Now we are looking for the signature: <code>void foo(MyClass&amp;, unsigned)</code></p> <pre><code>template&lt;class T&gt; struct has_foo { typedef char (&amp;Yes)[1]; typedef char (&amp;No)[2]; template&lt;class U&gt; static Yes test(U * data, MyClass* arg1 = 0, typename std::enable_if&lt;std::is_void&lt; decltype(data-&gt;foo(*arg1, 1u)) &gt;::value&gt;::type * = 0); static No test(...); static const bool value = sizeof(Yes) == sizeof(has_foo::test((typename std::remove_reference&lt;T&gt;::type*)0)); }; </code></pre> <p>Please notice that MyClass doesn't has to be default constructible or to satisfy any special concept. The technique works with template members, as well.</p> <p>I am eagerly waiting opinions regarding this.</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