Does std::bind discard type information of parameters in C++11?

前端 未结 1 1594
北荒
北荒 2021-01-19 13:55

Case where the problem occours

Please consider the following c++ code:

#include 
#include 
#inclu         


        
相关标签:
1条回答
  • 2021-01-19 14:27

    This is just object slicing. Pass the instance by reference:

    auto func = std::bind(&print, std::ref(instance));
    //                            ^^^^^^^^
    

    To explain this a bit more: Like most C++ standard library types, the result type of a bind expression owns all its bound state. This means you can take this value and pass it around freely and store it and come back to it later in a different context, and you can still call it with all its bound state ready for action.

    Therefore, in your code, the bind object was constructed with a copy of instance. But since instance wasn't a complete object, you caused slicing to happen.

    By contrast, my code copies a std::reference_wrapper<A> into the bind object, and that's essentially a pointer. It doesn't own the instance object, so I need to keep it alive as long as the bind object may get called, but it means that the bound call is dispatched polymorphically to the complete object.

    0 讨论(0)
提交回复
热议问题