为什么类可以被视为 std::function<float()> 但 shared_ptr 不能被视为 std::shared_ptr<std::function<float()>>>

Gue*_*OCs 0 c++ polymorphism

有一些代码能够将实现operator()std::function. 然后我尝试做同样的事情,但使用shared_ptr

#include <functional>
#include <memory>

class WhiteNoise  {
public:
    WhiteNoise()  {}
    float operator() () {
        return 0;
    }
};

int main() {
    //fails
    std::shared_ptr<std::function<float()>> = std::dynamic_pointer_cast<std::function<float()>>(std::make_shared<WhiteNoise>());
    //fails
    std::shared_ptr<std::function<float()>> = std::make_shared<WhiteNoise>();
    //works
    std::function<float()> f = WhiteNoise();
}
Run Code Online (Sandbox Code Playgroud)

为什么我可以WhiteNoise当作std::function<float()>但不能shared_ptr<WhiteNoise>当作shared_ptr<std::function<float()>>

Rem*_*eau 5

为什么我可以WhiteNoise当作std::function<float()>但不能shared_ptr<WhiteNoise>当作shared_ptr<std::function<float()>>

出于类似的原因,为什么 anint可以分配给 a double,但int*不能分配给 a double*。因为有定义的从int到的转换double,但是在不相关的指针类型之间没有定义的转换。

同样,有一个可调用函数对象到std::function. 该std::function将使对象的副本,并调用它的实施operator()需要的时候。

但是当本身不是 a时,没有定义从 a std::shared_ptr<T>(ie T*) 到 a std::shared_ptr<std::function>(ie std::function*)T的转换std::function

如果你有一个std::shared_ptr<WhiteNoise>并且你想从中得到一个std::shared_ptr<std::function<float()>>(为什么?),你可以做这样的事情:

auto wn = std::make_shared<WhiteNoise>();
auto func = std::make_shared<std::function<float()>>(*wn);
float f = (*func)();
Run Code Online (Sandbox Code Playgroud)