在这个程序中,我使用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());
}
Run Code Online (Sandbox Code Playgroud)
它似乎工作,但是,我担心这可能不适用于所有平台.另外我不确定我是否应该使用:
typeid(const Impl<std::string>&) // with ref
Run Code Online (Sandbox Code Playgroud)
代替
typeid(const Impl<std::string>) // without ref
Run Code Online (Sandbox Code Playgroud)
在比较功能中.
以上代码是否正确?如果没有,那么我该如何解决呢?
使用时typeid,它可以应用于表达式或类型.应用于类型时,如下所示:
引用表示类型类型的std :: type_info对象.如果type是引用类型,则结果引用表示引用类型的std :: type_info对象.
http://en.cppreference.com/w/cpp/language/typeid.因此,无论您是否使用该引用,它都没有任何区别.同样的消息来源继续说:
不能保证相同类型的typeid表达式的所有评估都会引用相同的std :: type_info实例,尽管那些type_info对象的std :: type_info :: hash_code将是相同的,就像它们的std: :type_index.
这意味着&typeid(impl)与其他东西相比,即使对象具有相同的动态类型,也可能返回false.因此,比较他们的地址并不是一个好的选择.您应该直接比较对象本身,即&从两侧移除运算符,因为std::type_info(返回typeid)已operator==定义.