Nick
Nick

Reputation: 25

Error with a function pointer as a map parameter? C++

I seem to be getting several errors with

map<string,function<XMLSerializable*()>> mapConstructor;

Notably,

 la5.cpp: In function ‘int main(int, char**)’:
 la5.cpp:21:13: error: ‘function’ was not declared in this scope
 la5.cpp:21:43: error: ‘mapConstructor’ was not declared in this scope
 la5.cpp:21:43: error: template argument 2 is invalid
 la5.cpp:21:43: error: template argument 4 is invalid
 la5.cpp:25:58: warning: lambda expressions only available with -std=c++0x or - std=gnu++0x [enabled by default]
 la5.cpp:33:26: error: expected primary-expression before ‘*’ token
 la5.cpp:33:28: error: expected primary-expression before ‘)’ token
 la5.cpp:33:31: error: ‘pFunc’ was not declared in this scope
 make: *** [la5.o] Error 1

Unfortunately, I can't seem to find what I've done wrong, as it seems to deal with that map declaration which was given to the class by my instructor. Below is my .cpp

#include <iostream>
#include <map>
#include <string>
#include <functional>

#include "Armor.h"
#include "Weapon.h"
#include "Item.h"
#include "Creature.h"

using namespace std;

XMLSerializable * constructItem()
{
        return new Item;
}

int main(int argc, char * argv[])
{

    map<string,function<XMLSerializable*()>> mapConstructor;

    mapConstructor["Item"] = constructItem;

    mapConstructor["Creature"] = []() {return new Creature; };

    cout << "Input the class name, then we'll try to construct it." << endl;

    string sLookup = " ";

    cin >> sLookup;

    function<XMLSerializable*()> pFunc = mapConstructor[sLookup];

    if(pFunc() == NULL)
    {
            cout << "Sorry, the object couldn't be constructed." << endl;
    }
    else
    {
            cout << pFunc() << " a non NULL value was returned!" << endl;
    }
    return 0;
}

Any suggestions? I'm unfamiliar with maps, but I believe this should work, right?

Coding in pico, compiling with a makefile using g++.

Upvotes: 1

Views: 254

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

It looks like you just are forgetting to add -std=c++11 or -std=c++0x to your compiler flags to enable C++11.

-std=c++0x is deprecated, but on older versions of g++, -std=c++11 is not available.

Upvotes: 1

Related Questions