Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I create a predicate that will accept both functions and functors as a parameter?
    primarykey
    data
    text
    <p>I'm working on a problem in C++ that involves lots of subset and transformation operations on a large quantity of data. To that end, I've created a map function and something like list comprehensions. I've found that a bunch of the predicates I'm writing also have inverses, so I'd need to write:</p> <pre><code>template &lt;typename type_t&gt; bool HasTenFoo(const type_t &amp;t) { return t.foo &gt;= 10.0; } </code></pre> <p>and</p> <pre><code>template &lt;typename type_t&gt; bool DoesntHaveTenFoo(const type_t &amp;t) { return t.foo &lt; 10.0; } </code></pre> <p>Neither of those is a real example, but they're representative. I'm also using a fair number of functors like:</p> <pre><code>class HasEnoughFoo { public: HasEnoughFoo (double bar) { this-&gt;bar = bar; } template&lt;typename type_t&gt; bool operator()(const type_t &amp;t) const { return t.foo &gt;= bar; } private: double bar; }; </code></pre> <p>some of which should have inverses as well. Rather than duplicate code unnecessarily, I'd like to write a functor that takes a predicate as an argument and returns the (value of the) inverse of that predicate. My fist cut at one is below:</p> <pre><code>/* -- Returns the opposite of some other predicate -------------------------- */ template&lt;typename predicate_t&gt; class Not { public: template &lt;typename predicate_t&gt; Not(predicate_t *p) { predicate = p; } template &lt;typename type_t&gt; bool operator()(const type_t &amp;t) const { return !(*predicate)(t); } private: predicate_t *predicate; }; </code></pre> <p>I would call that with something like:</p> <pre><code>new_list = old_list.subset(Not&lt;HasEnoughFoo&gt;(&amp;HasEnoughFoo(10.0)); </code></pre> <p>or</p> <pre><code>new_list = old_list.subset(Not&lt;HasTenFoo&gt;(&amp;HasTenFoo)); </code></pre> <p>That seems to work well when <code>predicate_t</code> is a functor like <code>HasEnoughFoo</code>, but fails when <code>predicate_t</code> refers to a regular function like <code>HasTenFoo</code>.</p> <p>Visual Studio complains that <code>'HasTenFoo' is not a valid template type argument for parameter 'predicate_t'</code>. Is there any way to write a Not() predicate that will work with functors and functions or am I doomed to write dozens of predicates and their inverses as well?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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