Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I use boost::enable_if on a member function?
    text
    copied!<p>I'm writing a template class, and I want to allow an additional method to exist only for a certain template type. Currently the method exists for all template types, but causes a compilation error for all other types.</p> <p>Complicating this is that it's an overloaded operator(). Not sure if what I want to do is actually possible here.</p> <p>Here's what I have now:</p> <pre><code>template&lt;typename T, typename BASE&gt; class MyClass : public BASE { public: typename T&amp; operator() (const Utility1&lt;BASE&gt;&amp; foo); typename T const&amp; operator() (const Utility2&lt;BASE&gt;&amp; foo) const; }; </code></pre> <p>I want the <code>T&amp;</code> version always available, but the <code>T const&amp;</code> version only available if <code>Utility2&lt;BASE&gt;</code> is valid. Right now, both methods exist, but attempting to use the const version gives a weird compilation error if <code>Utility2&lt;BASE&gt;</code> is invalid. I'd rather have a sensible error, or even a "no such member function" error.</p> <p>Is this possible?</p> <p><strong>EDIT</strong>: After reading through the boost docs, here's what I've come up with, and it seems to work:</p> <pre><code>template&lt;typename T, typename BASE&gt; class MyClass : public BASE { public: typename T&amp; operator() (const Utility1&lt;BASE&gt;&amp; foo); template&lt;typename U&gt; typename boost::enable_if&lt;boost::is_same&lt;Utility2&lt;BASE&gt;, U&gt;, T&gt;::type const &amp; operator() (const U&amp; foo) const; }; </code></pre> <p>So that method doesn't exist unless someone tries to use it with Utility2, and they can only create a Utility2 if it's valid for that BASE type. But when it's not valid for that BASE type, MyClass will not waste time creating the accessor method.</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