在這個程序中,我使用的typeid檢查對象的派生類型:比較typeid的指針
#include <cstdint>
#include <memory>
#include <cassert>
#include <string>
#include <typeinfo>
struct Wrap
{
explicit Wrap(int64_t id) : mImpl(new Impl<int64_t>(id)) {}
explicit Wrap(std::string id) : mImpl(new Impl<std::string>(std::move(id))) {}
bool isInt64() const
{
const ImplBase& impl = *mImpl;
return (&typeid(impl) == &typeid(const Impl<int64_t>));
}
bool isString() const
{
const ImplBase& impl = *mImpl;
return &typeid(impl) == &typeid(const Impl<std::string>);
}
private:
struct ImplBase
{
virtual ~ImplBase() {}
};
template<typename T>
struct Impl : ImplBase
{
Impl(T value) :
mValue(std::move(value))
{
}
T mValue;
};
std::shared_ptr<const ImplBase> mImpl;
};
int main()
{
Wrap r1(int64_t(1));
assert(r1.isInt64());
Wrap r2(std::string("s"));
assert(r2.isString());
}
看來工作,但是,我擔心這可能不會在所有平臺上工作。另外,我不知道我是否應該使用:的
typeid(const Impl<std::string>&) // with ref
代替
typeid(const Impl<std::string>) // without ref
在比較功能。
上述代碼是否正確?如果沒有,那我該如何解決它?
爲什麼VT中的typeid字段存儲引用類型? – Arunmu
@阿努木好點,我沒有考慮過。 – StackedCrooked