vendredi 29 avril 2016

Using RTTI hash with a template function

I understand that templates are compile-time, and typeinfo-related are runtime, but I'm wondering if I can achieve my particular task.

I have a factory method using templates to create objects of a particular type; I also have a preloader (reading data from disk), which determines what type of object is to be created, but doesn't actually create it - that's the responsibility of the creator, and is executed on demand.

void Creator::Spawn(Preloader* pl)
{
    std::unordered_map<size_t, std::type_index>   hashmap;

    // assume ObjectType is simply a wrapper around a hash
    hashmap[ObjectType<Type1>::GetType().Hash()] = typeid(Type1);
    hashmap[ObjectType<Type2>::GetType().Hash()] = typeid(Type2);

    for ( auto& const i : pl->GetPreloadInfo() )
    {
        size_t  hash = i->type_hash.Hash();

        // similar-to-desired usage
        FactoryCreate<hashmap[hash]>();
    }
}

Is there any way to achieve this? Obviously I can do manual checks for each, like below, but it's nasty at best.

        // poor, manual implementation
        if ( hash == ObjectType<Type1>::GetType().Hash() )
            FactoryCreate<Type1>();
        else if ( hash == ObjectType<Type2>::GetType().Hash() )
            FactoryCreate<Type2>();

Everything I've tried so far has hit the runtime vs compile-time differences, though I'm definitely not aware of all the newest C++11 tricks that may assist (C++14 not usable).

Partially related question here: Use data type (class type) as key in a map

Aucun commentaire:

Enregistrer un commentaire