In this program, I use typeid to test the derived type of an object:
#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());
}
It seems to work, however, I'm worried that this may not work on all platforms. Also I'm not sure what I should use:
typeid(const Impl<std::string>&)
instead
typeid(const Impl<std::string>)
in comparison functions.
Is the above code correct? If not, how can I fix this?
source
share