Skip to main content
2 of 2
added 247 characters in body
G. Sliepen
  • 61.7k
  • 3
  • 61
  • 152

Overhead of std::function

The main problem is that you are using std::function, and this comes with some overhead. In particular, it will allocate storage (using new internally) since your lambdas are capturing variables. Since memory allocations can have side effects (they might even throw exceptions if memory could not be allocated), the compiler cannot optimize them away.

Consider just storing the state of a pin as a bool

The state of an output pin is just true or false. Instead of storing a function that calculates the state, consider just storing the current state in a bool. It seems unlikely to me that always ensuring the state of the pin is set correctly is less efficient than having a function that calculates it whenever you need the value. An InputPin should then not store a copy of an OutputPin, but either a reference to an OutputPin, or if you want to still be able to have an expression assigned to an InputPin, have it store the function that calculates the input value. Once you do this, everything simplifies enormously, and the compiler will have no trouble optimizing this code.

Here is an example:

#include <functional>

using OutputPin = bool;

template<typename Function>
class InputPin {
    Function f;

public:
    InputPin(const Function &f): f(f) {}

    operator bool() const {
        return f();
    }
};

int main()
{
        OutputPin   a(true), b(true), c(true);
        InputPin    i([&]{return !a & b & c;});
    
        return i;
}
G. Sliepen
  • 61.7k
  • 3
  • 61
  • 152