3

I am curious as to how std::function can accept objects of different types as long as they have the same function call operator signature. For instance, these two structs are clearly unrelated, and yet, the same std::function object can be assigned to both of them.

struct A {
    int operator()(int a) {
        return a;
    }
};

struct B {
    int operator()(int a) {
        return a;
    }
};

int main() {
    function<int(int)> f;
    f = B{}; //OK
    f = A{}; //OK
}

Could someone explain how is this possible?

GamefanA
  • 1,555
  • 2
  • 16
  • 23
  • 1
    You can try having a first stab at it by reading the source code of the `` header from your standard library :) -- The general name of the technique is *type erasure*. – Quentin Dec 10 '18 at 10:58

0 Answers0