为什么类可以被视为std::function<float()>但shared_ptr不能被视为std::shared_ptr<std::function<float()>>>
有一些代码能够将实现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();
}
为什么我可以WhiteNoise当作std::function<float()>但不能shared_ptr<WhiteNoise>当作shared_ptr<std::function<float()>>
回答
为什么我可以
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)();
THE END
二维码