0

I have this class:

class LevelParser  
{  
    private:
        int tileSize;
        std::vector<Tileset>* pTilesets;

        typedef LayerABC* (*pFunc)();

        std::unordered_map<std::string, pFunc> layerFactory;

        template <typename T>
        void registerLayer(std::string layerName);

        LayerABC* createLayer(std::string layerName);
};

template <typename T>
void LevelParser::registerLayer(std::string layerName)
{
    auto Iterator = layerFactory.find(layerName);

    if(Iterator != layerFactory.cend())
    {
        return;
    }

    layerFactory[layerName] = [&] () -> LayerABC* {return new T(tileSize, pTilesets); };
}

It compiles okay, but when it comes to creating a layer via factory, the program brakes and IDE points me to the line with lambda of the 'registerLayer' function.

The LevelParser class variables 'tileSize' and 'pTilesets' get initialised later during the parsing process and before the layer creation happens, that is why they are captured by reference, and that is why lambda should work, but it does not.

Does anyone have idea what is wrong?

P.S.
There is a solution to avoid passing parameters to the layer constructor like this:

layerFactory[layerName] = [] () -> LayerABC* {return new T(); };

and initialise the object after construction via an 'init(int, std::vector<Tileset>*)' function that will actually duplicate the initialisation job that is done by the constructors - but this is the second resort.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
tolerance
  • 11
  • 3
  • It should not compile. Only a lambda that doesn't capture anything is convertible to a plain pointer-to-function. – Igor Tandetnik Sep 28 '15 at 16:35
  • You could have the lambda take `tileSize` and `pTilesets` (or `LevelParser *` pointer) as parameters, instead of capturing them, then pass them along to `T`'s constructor same as you try now. Just change the definition of `pFunc`. – Igor Tandetnik Sep 28 '15 at 16:38
  • See [Passing lambda as function pointer](http://stackoverflow.com/q/28746744/1708801) – Shafik Yaghmour Sep 28 '15 at 16:48
  • You are not capturing member variables. You are capturing **this**. You better capture it by value, because it's local to the function. – n. m. could be an AI Sep 28 '15 at 17:08
  • [Posaible duplicate](http://stackoverflow.com/questions/17197997/lambda-captures-and-member-variables). – n. m. could be an AI Sep 28 '15 at 17:19
  • Thanks everybody for the input. – tolerance Sep 29 '15 at 12:50
  • @IgorTandetnik, as per your suggestion I expanded the definition of `pFunc` to `typedef LayerABC* (*pFunc)(LevelParser*);`, made the subsequent changes to the code where needed, and got rid of a crash, as expected. You said it should not have compiled, but it actually did with gcc4.7.1 compiler. – tolerance Sep 29 '15 at 12:59

0 Answers0