Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting an neutral element for std::multiply and std::plus

While implementing a template class whose constructor takes:

  1. vector of functions (functions are of type std::function<bool(const T&)>)
  2. std::binary_function<bool,bool,bool> that I will use to accumulate results of applications of vector from 1) to certain value.

I want to be able to use std::plus() and std::multiplies() as second template parameter, but the problem is that depending on the function I need a corresponding neutral element (for std accumulate init value). For AND (std::multiplies) I need true (aka 1), for OR (std::plus) I need false (aka 0). I know I could just specialize the template and problem solved but I wonder if there is a way to get neutral element for a built in STL function.

like image 505
NoSenseEtAl Avatar asked Dec 10 '25 16:12

NoSenseEtAl


1 Answers

If you're using gcc, you can use __gnu_cxx::identity_element, which is doing exactly what you're asking for.

If you're not, I don't think there is a general solution, as if there was, gcc wouldn't have implemented their own - you might just rewrite their implementation (which is actually just a couple of template specializations, as you expected).

Edit: the source code for this is on lines 78-98 of this file.

like image 78
Ivan Vergiliev Avatar answered Dec 12 '25 05:12

Ivan Vergiliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!