user3207838
user3207838

Reputation: 676

pybind11 variable return type

I have a C++ class which acts like a map that can contain different data types.

In C++, it is unknown at compile time what data type an entry is. Therefore, the programmer has to know and the accessor is templated:

auto a = map.get<int>("my-int-entry");
auto b = map.get<std::string>("my-string-entry");

At runtime, the map knows what type the entries have. So in python, I should be able to use the runtime type information.

a = map.get('my-int-entry') # a is of type int
b = map.get('my-string-entry') # b is of type string

I'd like that it looks up the type information at runtime, then calls get<int> if the runtime type is int, otherwise get<std::string>. Is there a way to do this directly in pybind11? Or do I need another (pure python) function that calls the respectively mapped C++ functions?

Upvotes: 0

Views: 334

Answers (1)

unddoch
unddoch

Reputation: 6004

I'm not sure how you would query your map in runtime about what type a key has, but this is the general idea of how I would do that:

map_wrapper.def("get", [](Map& self, const std::string& key) -> py::object {
  if (self.is_a<int>(key)) {
    return py::cast(self.get<int>(key));
  } else if (self.is_a<std::string>(key)) {
    return py::cast(self.get<std::string>(key));
  } else if ...
});

You would need to know the types you want to support in advance.

Upvotes: 1

Related Questions