假设我有一个指定转换为 int 的类 A
struct A {
int val = 42;
operator int() const {
return val;
}
所以我可以这样使用它:
A a;
int a_int = a;
但是如果我想使用指向该类的共享指针怎么办:
auto a_ptr = std::shared_ptr<A>(new A);
int a_int = a_ptr; // ???
就像类型 A 的变量被隐式转换为 int 我想对智能指针做同样的事情。 我怎样才能做到这一点?
更新
对不起,我可能问错了。 真正的交易有点复杂。 我使用 QVariant 来保存 std::shared_ptr。 现在我有一个辅助函数可以做到这一点:
QVariant & operator<< (QVariant& v, const std::shared_ptr<A> & aPtr);
当我需要将指针指向 QVariant 时,我会这样做:
QVariant variant = QVariant() << a_ptr;
但我想自动完成,像这样:
QVariant variant = a_ptr;
最佳答案
你试过了吗?
std::shared_ptr
具有 operator*
并且它的工作方式正如人们所期望的那样:使用它。
#include <memory>
struct A {
int val = 42;
operator int() const {
return val;
}
};
int main() {
auto ptr = std::make_shared<A>();
int v = *ptr;
}
关于c++ - 将 std::shared_ptr 隐式转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667493/