'Store an instance of a different classes in a map

I want to be able to store an instance of a different classes in a map so that I can add, delete and access the instances outside of the entity class.

This is what I have tried so far..

#pragma once
#include <iostream>
#include <string>
#include <any>
#include <map>
#include "position.h"


class Entity
{
public:
    //Entity();
    //~Entity();

    template <typename T>
    void addComponent()
    {
        T c;
        components[typeid(T).name()] = c;
    }

    template <typename T>
    void print()
    {
        T c = components[typeid(T).name()];
        c.print();
    }



private:
    std::map<std::string, std::any> components;
};

int main()
{
    Entity entity;
    entity.addComponent<positionComponent>();
    entity.print<positionComponent>();
return 0;

}

and in position.h:


#pragma once

#include <iostream>

class positionComponent
{
public:
    //positionComponent(const char* a)
    //{
    //  std::cout << a << std::endl;
    //}
    //~positionComponent();

    void print() 
    {
        std::cout << "printing" << std::endl;
    }

private:

};

As you can guess this doesn't work. I get the error:

Severity Code Description Project File Line Suppression State Error C2440 'initializing': cannot convert from 'std::any' to 'T' test.c 25

c++


Sources

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

Source: Stack Overflow

Solution Source