Juan
Juan

Reputation: 2103

String to data type class

I want convert a string to datatype class, for this I use a reference. Then I trying use a map than the follow code. But when I trying compile this I get

Error message:

error: invalid conversion from 'std::map, void* (*)()>::mapped_type {aka void* ()()}' to 'void' [-fpermissive]

Code:

class C1 {
public:
  C1() { std::cout << "Object of class C1 created\n"; }
  static void * create() { return (void*)new C1; }
};

class C2 {
public:
C2() { std::cout << "Object of class C2 created\n"; }
static void * create() { return (void*)new C2; }
};

typedef void * (*fptr)();

int main() {
  std::map<std::string, fptr> fpmap;
  fpmap.insert(std::make_pair(std::string("C1"), C1::create));
  fpmap.insert(std::make_pair(std::string("C2"), C2::create));

  std::string classname;
  std::cout << "Insert classname :" << std::flush;
  std::cin >> classname;

  void * obj = fpmap["C1"];
}

Upvotes: 0

Views: 88

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Did you mean:

void * obj = fpmap["C1"]();

A function pointer isn't directly convertible to a void*. I you want obj to point to the function itself, declare it as fptr. If you want to call the function and have obj point to what it returns, you need to call the function (extra ()).

Upvotes: 4

Related Questions