"offer a generic, statically bound interface, but internally dispath dynamically, so you offer a uniform object layout"?

Hi,

pg 121 of C++ Coding Standards book has this assertion, but I fail to understand it completely.

Any help appreciated!!


Thanks,
Juan
The next sentence gives shared_ptr's type-erased Deleter as an example, which suggests that they are talking about type erasure. Other popular example of this technique are C++11's std::function and C++17's std::any (aka boost.any).
ok, but looking at std::function (see code sample below) where is the internally dynamic dispatch - I don't see any polymorphism here... (sorry I am probably a bit tired)

1
2
3
4
5
6
7
    // store a free function
    std::function<void(int)> f_display = print_num;
    f_display(-9);
 
    // store a lambda
    std::function<void()> f_display_42 = []() { print_num(42); };
    f_display_42();


Please elaborate a bit! :-)

Thanks
Juan

OR: can you provide a very simple example where the combination of static and dynamic polymorphism is evident?)
Last edited on
std::function::operator() calls a virtual function.

Note how the size (and the type) of std::function<int(void)> never changes ("uniform object layout") no matter what type/size callable it stores:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <functional>
auto lam = [](int n){ std::cout << n << '\n'; };
void fun(int n) { std::cout << n << '\n'; }
struct Fatfun { int data[1024]; void operator()(int n) const { std::cout << n << '\n'; }} fatfun;
int main()
{
    std::function<void(int)> f1 = lam, f2 = &fun, f3 = fatfun;
    std::cout << "sizeof: lam = " << sizeof lam << " fun = " << sizeof &fun << " fatfun = " << sizeof fatfun << '\n'
              << "         f1 = " << sizeof f1  << "  f2 = " << sizeof f2  << " f3 = " << sizeof f3 <<'\n';
}

http://coliru.stacked-crooked.com/a/4eb0b0946935e62b
sizeof: lam = 1 fun = 8 fatfun = 4096
         f1 = 32  f2 = 32 f3 = 32
Last edited on
Great!!!

Thanks

Juan
Topic archived. No new replies allowed.