sajal
sajal

Reputation: 91

Using static maps within a class inside different functions:

I have a class like this:

class SelectorFactory
{
public:

    static std::map<std::string,int> _creator;  
    static void registerCreator(std::string& name,int value)
    {
    //static std::map<std::string,int> _creator;
        if(_creator.end() != _creator.find(name))
        {
           std::cout << "Selector already registered \n";
        }
    else
    {
        std::cout << "Entering " <<name<<" in register: \n";
        _creator[name]=value;
    }
    }   

    static int createSelector(std::string selectorName)
    {
    //static std::map<std::string,int> _creator;
        std::map< std::string , int >::iterator mapIter=_creator.find(selectorName);
        if(mapIter==_creator.end())
        {
            std::cout<<selectorName<<" Not found in the Map \n" ;
            return 0;
        }
        else
        {
            int selector= mapIter->second;
            return selector;
        }
    }
};

If I uncomment the commented lines above, code is getting compiled but it's not returning any value from createSelector function which is quite obvious.But if I keep them commented, I am getting error as "_creator was not declared in this scope" inside both the functions. What should I do to rectify this issue.

Upvotes: 0

Views: 99

Answers (2)

Alex
Alex

Reputation: 91

SelectorFactory.h :

#ifndef __SELECTOR_FACTORY__H__
#define __SELECTOR_FACTORY__H__
#include <string>
#include <map>

class SelectorFactory
{
public: 
    static void registerCreator(std::string& name,int value); 
    static int createSelector(std::string selectorName);
private:              // !!!!!!!!! NOT PUBLIC!!!   >:(
    static std::map<std::string,int> _creator;   

};
#endif // __SELECTOR_FACTORY__H__

SelectorFactory.cpp :

#include "SelectorFactory.h"
#include <iostream>

std::map<std::string,int> SelectorFactory::_creator; 

void SelectorFactory::registerCreator(std::string& name,int value)
{
    if(_creator.end() != _creator.find(name))
    {
        std::cout << "Selector already registered \n";
    }
    else
    {
        std::cout << "Entering " <<name<<" in register: \n";
        _creator[name]=value;
    }
}   

int SelectorFactory::createSelector(std::string selectorName)
{
    std::map< std::string , int >::iterator mapIter=_creator.find(selectorName);
    if(mapIter==_creator.end())
    {
        std::cout<<selectorName<<" Not found in the Map \n" ;
        return 0;
    }
    else
    {
        int selector= mapIter->second;
        return selector;
    }
}

Upvotes: 1

ogni42
ogni42

Reputation: 1276

In order to have -creator instantiated, you must provide a definition for it. Currently, you have only a declaration.

class SelectorFactory
{
    static std::map<std::string,Int> _creator;
};
std::map<std::string,Int> SelectorFactory::_creator;

Upvotes: 1

Related Questions