'Casting base class to templated derived class

I am trying to create a map where types can be accessed based on their type. I am having issues getting the code to compile.

#include <iostream>
#include <typeindex>
#include <map>

struct ITest {
};

template <class T>
struct Test : public ITest {
};

struct Vertex {
    int x;
    int y;
    int z;
};

std::map<std::type_index, ITest> m;

template <typename T>
void add() {
    m[typeid(T)] = Test<T>();
}

template <typename T>
Test<T> get() {
    // The compiler doesn't like this line. All I'm trying to do is get the base         
    // class via the type id, then cast it to the templated derived class
    return static_cast<Test<T>>(m[typeid(T)]);
}

int main() {
    add<Vertex>();
    Test<Vertex> v = get<Vertex>();

    return 0;
}

The following is the error being generated using GCC 9.4.0 and compiling for C++17.

error: no matching function for call to ‘Test<Vertex>::Test(std::map<std::type_index, ITest>::mapped_type&)’

return static_cast<Test<T>>(m[std::type_index(typeid(T))]);

I'm not really sure what the issue with this line is. I'm indexing via the id of the type and casting the ITest to a templated Test. This question is pretty straightforward. If you can help me getting this to compile that would be great. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source