Type Pointer Comparison

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>&) // with ref

instead

typeid(const Impl<std::string>) // without ref

in comparison functions.

Is the above code correct? If not, how can I fix this?

+4
source share
1 answer

When used, typeidit can be applied to an expression or type. When applied to a type, like yours:

Refers to the std :: type_info object representing the type of the type. If the type is a reference type, the result is for the std :: type_info object representing the reference type.

http://en.cppreference.com/w/cpp/language/typeid. , . :

, std:: type_info typeid type, std:: type_info:: hash_code type_info , std:: type_index.

, &typeid(impl) - false, . . , .. & , std::type_info ( typeid) operator==.

+5

Source: https://habr.com/ru/post/1661172/


All Articles