std::map accessors with std::shared_ptr?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
Report Content as Inappropriate

std::map accessors with std::shared_ptr?

Steve Skutnik
Hello SWIG folks,

I'm having a bit of a tricky issue involving using the std::map accessor functions in Python when this type is represented as a std::shared_ptr type. Specifically, I cannot seem to use the typical [ ] accessor when a type derived from std::map is represented as a shared pointer; however, this doe appear to work when it's simply a regular pointer.

I created a minimum working example to demonstrate the issue.

First, a C++ class declaration, including a class (which I intend to use with a shared_ptr) and then a type I'm deriving from std::map


#include <iostream>
#include <map>
#include <memory>

class fooType{
  fooType() { };
  ~fooType() { };
  void printFoo() { std::cerr << "FOO!" << std::endl; }
  static std::shared_ptr<fooType> make_shared() {
      return std::shared_ptr<fooType>(new fooType());

class testMap : public std::map<int, std::shared_ptr<fooType> > {
   void printBar() { std::cerr << "bar." << std::endl; }

Then I have my SWIG interface file (TestMap.i):

%module TestMap

%include <std_map.i>
%include <std_shared_ptr.i>

#include "TestMap.h"

%shared_ptr(std::map<int, std::shared_ptr<fooType> > );

%template(fooMap) std::map< int, std::shared_ptr<fooType> >;

%include "TestMap.h"

Finally, the python script I'm using to test things out:

import TestMap as tm

ft = tm.fooType.make_shared()
myTestMap = tm.testMap()

myTestMap[1] = ft
When I try to use the accessor function (i.e., myTestMap[1] = ft), I get the following error:

Traceback (most recent call last):
  File "", line 9, in <module>
    myTestMap[1] = ft
  File "/home/sskutnik/tstSWIG/", line 217, in __setitem__
    return _TestMap.fooMap___setitem__(self, *args)
 NotImplementedError: Wrong number or type of arguments for overloaded function 'fooMap___setitem__'.
   Possible C/C++ prototypes are:
     std::map< int,std::shared_ptr< fooType > >::__setitem__(std::map< int,std::shared_ptr< fooType > >::key_type const &)
     std::map< int,std::shared_ptr< fooType > >::__setitem__(std::map< int,std::shared_ptr< fooType > >::key_type const &,std::map< int,std::shared_ptr< fooType > >::mapped_type const &

Note that if I don't include the declaration of testMap (my type derived from std::map) as a shared_ptr, the accessor works perfectly fine.

So, my question is - why does this fail if testMap is declared as a shared_ptr type, and how can I work around this?

Steve Skutnik, Ph.D.

Check out the vibrant tech community on one of the world's most
engaging tech sites,!
Swig-user mailing list
[hidden email]