I have a map in C++ and I wish to input my class as the value, and a string as the key.
When I try to, I get an error 'Scene_Branding' : illegal use of this type as an expression
I get an illegal use of this type as an expression, and I can't seem to find out why. Here is some code.
string CurrentScene = "Scene_Branding";
map<string, Scene> Scenes;
Scenes.insert(std::make_pair("Scene_Branding", Scene_Branding)); //<-- Illegal Error parameter 2
and here is Scene Branding header..
#ifndef Scene_Branding_H
#define Scene_Branding_H
#include "Scene.h"
#include <iostream>
#include <string>
class Scene_Branding : Scene
{
public:
Scene_Branding();
~Scene_Branding();
void Draw();
};
#endif
and here is Scene header..
#ifndef Scene_H
#define Scene_H
#include <iostream>
#include <string>
class Scene
{
public:
Scene();
~Scene();
virtual void Draw();
};
#endif
and here is there cpp files.
Scene cpp.
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
}
void Scene::Draw(){
std::cout << "Hey";
}
Scene_Branding cpp
#include "Scene_Branding.h"
Scene_Branding::Scene_Branding()
{
}
Scene_Branding::~Scene_Branding()
{
}
void Scene_Branding::Draw()
{
std::cout << "Drawing from Scene_branding";
}
The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn't exist. If the key already exists in the map, the element is not inserted.
Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.
insert() doesn't overwrite.
insert( make_pair( std::move(key), std::move(value) ) ) is going to be close to map. emplace( std::move(key), std::move(value) ) . If there is an object at the key location, then [] will call operator= , while insert / emplace will destroy the old object and create a new one.
First, don't store objects themselves in the map, store pointers to your objects.
Second, you need to give an instance of Scene_Branding to std::make_pair, not the class itself.
EDIT: Here's how you go about storing pointers:
string CurrentScene = "Scene_Branding";
map<string, Scene*> Scenes;
Scenes.insert(std::make_pair("Scene_Branding", new Scene_Branding()));
But, since you asked this type of question, i recommend you read a good c++ book for further grasping of concepts like pointers.
Try:
Scenes.insert(std::make_pair("Scene_Branding", Scene_Branding()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With