std::shared_ptr<T>
いろいろなタイプに使っています。shared_ptr
これらの異なるすべてを1つのベクトルに格納したいので、必要に応じてastd::vector<std::shared_ptr<void> >
とキャストを使用することを考えましたvoid
。
私は次の「ベアポインタ」の使用法に精通しています
#include <iostream>
void print(void* void_ptr)
{
int* int_ptr = static_cast<int*>(void_ptr);
std::cerr << *int_ptr << std::endl;
}
int main()
{
int* int_ptr = new int(4);
void* void_ptr = static_cast<void*>(int_ptr);
print(void_ptr);
delete int_ptr;
}
これは問題なく機能しg++
、ポインタが裸の場合にこれを行うのに適切な方法です。しかし今、私はsと同じようにしたいですstd::shared_ptr
。
#include <iostream>
#include <memory>
void print(std::shared_ptr<void> void_ptr)
{
std::shared_ptr<int> int_ptr = ??(void_ptr); // simple cast won't work
std::cerr << *int_ptr << std::endl;
}
int main()
{
std::shared_ptr<int> int_ptr = std::make_shared<int>(4);
std::shared_ptr<void> void_ptr = ??(int_ptr); // same problem here
print(void_ptr);
}
これも可能ですか?私がしなければならないさまざまなタイプがたくさんありますがshared_ptr
、これらのタイプにはほとんど共通点がありません。彼らは基本クラスなどを共有していません(それが唯一の方法である場合、私はそれを行いますが、ある種の方法で間違いなくもっと素晴らしいでしょうshared_ptr<void>
)。