SFINAE To detect non-member function existence
<p>Does anybody know of a method for specializing a template depending on whether a non-member method is defined? I know there are numerous ways for specializing if a member function exists, but I've never seen a non-member example. The specific problem is specializing the operator&lt;&lt; for shared_ptr to apply the operator&lt;&lt; if the operator&lt;&lt; is defined for T, and printing the mere pointer location otherwise. It would be great if all classes defined operator&lt;&lt; as a member, but unfortunately many use free functions. I'm imagining something like the following:</p>

<pre><code>template &lt;typename T&gt;
typename enable_if&lt; ??? ,std::ostream &amp;&gt;::type operator&lt;&lt;( std::ostream &amp; os, const shared_ptr&lt;T&gt; &amp; ptr )
{
  if(ptr)
   return os &lt;&lt; *ptr;
  else
   return os &lt;&lt; "&lt;NULL&gt;";
}

template &lt;typename T&gt;
typename disable_if&lt; ??? ,std::ostream &amp;&gt;::type operator&lt;&lt;( std::ostream &amp; os, const shared_ptr&lt;T&gt; &amp; ptr )
{
  if(ptr)
   return os &lt;&lt; static_cast&lt;intptr_t&gt;( ptr.get() );
  else
   return os &lt;&lt; "&lt;NULL&gt;";
}
</code></pre>

<p>Edit: For posterity, here was the working solution. Note that boost::shared_ptr already has a default operator&lt;&lt; that outputs the address, so the disable_if is unnecessary. Since the operator&lt;&lt; returns a reference, this works. For the general case I suspect this would have to be tailored to reflect the return type of the function in question.</p>

<pre><code>template &lt;typename T&gt;
typename boost::enable_if_c&lt; boost::is_reference&lt;decltype(*static_cast&lt;std::ostream *&gt;(0) &lt;&lt; *static_cast&lt;T *&gt;(0) )&gt;::value, std::ostream &amp;&gt;::type operator&lt;&lt;( std::ostream &amp; os, const boost::shared_ptr&lt;T&gt; &amp; ptr )
{
  if(ptr)
   return os &lt;&lt; *ptr;
  else
   return os &lt;&lt; "&lt;NULL&gt;";
}
</code></pre>
