为什么 class 可以被当作 std::function<float()> 而 shared_ptr 不能被当作 std::shared_ptr<std::function<float()>>
Why class can be treated as std::function<float()> but shared_ptr cannot be treated as std::shared_ptr<std::function<float()>>
有些代码能够将实现 operator()
的 class 视为 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()>>
Why I can treat WhiteNoise
as std::function<float()>
but not shared_ptr<WhiteNoise>
as shared_ptr<std::function<float()>>
出于类似的原因,为什么 int
可以分配给 double
,但 int*
不能分配给 double*
。因为从int
到double
有一个定义的转换,但是不相关的指针类型之间没有定义的转换
同样,有一个可调用函数对象到 std::function
的定义转换。 std::function
将复制对象,并在需要时调用其实现的 operator()
。
但是当 T
不是它自己时,没有定义从 std::shared_ptr<T>
(即 T*
)到 std::shared_ptr<std::function>
(即 std::function*
)的转换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)();
有些代码能够将实现 operator()
的 class 视为 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()>>
Why I can treat
WhiteNoise
asstd::function<float()>
but notshared_ptr<WhiteNoise>
asshared_ptr<std::function<float()>>
出于类似的原因,为什么 int
可以分配给 double
,但 int*
不能分配给 double*
。因为从int
到double
有一个定义的转换,但是不相关的指针类型之间没有定义的转换
同样,有一个可调用函数对象到 std::function
的定义转换。 std::function
将复制对象,并在需要时调用其实现的 operator()
。
但是当 T
不是它自己时,没有定义从 std::shared_ptr<T>
(即 T*
)到 std::shared_ptr<std::function>
(即 std::function*
)的转换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)();