Skip to content

Instantly share code, notes, and snippets.

@adolfo-rt
Created July 14, 2014 15:23
Show Gist options
  • Save adolfo-rt/91d4d3566101a29ead6c to your computer and use it in GitHub Desktop.
Save adolfo-rt/91d4d3566101a29ead6c to your computer and use it in GitHub Desktop.
Example of how to store different types in a map using void shared pointers, while preserving correct destructors.
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <boost/shared_ptr.hpp>
class Foo
{
public:
~Foo() {std::cout << "Foo destructor" << std::endl;}
static std::string name() {return "Foo";}
};
class Bar
{
public:
~Bar() {std::cout << "Bar destructor" << std::endl;}
static std::string name() {return "Bar";}
};
class Baz
{
public:
~Baz() {std::cout << "Baz destructor" << std::endl;}
static std::string name() {return "Baz";}
};
typedef boost::shared_ptr<void> PtrType;
typedef std::map<std::string, PtrType> MapType;
template <typename T>
void test(const MapType& map)
{
if (map.find(T::name()) == map.end())
{
std::cout << T::name() << " not found" << std::endl;
}
else
{
std::cout << T::name() << " found" << std::endl;
}
}
int main()
{
MapType map1, map2, map12;
map1[Foo::name()] = PtrType(new Foo());
map1[Bar::name()] = PtrType(new Bar());
map2[Baz::name()] = PtrType(new Baz());
map12.insert(map1.begin(), map1.end());
map12.insert(map2.begin(), map2.end());
// map1 has Foo and Bar
std::cout << "*** Testing map1 ***" << std::endl;
test<Foo>(map1);
test<Bar>(map1);
test<Baz>(map1);
// map2 has Baz
std::cout << "\n*** Testing map2 ***" << std::endl;
test<Foo>(map2);
test<Bar>(map2);
test<Baz>(map2);
// map12 has Foo, Bar, Baz
std::cout << "\n*** Testing map12 ***" << std::endl;
test<Foo>(map12);
test<Bar>(map12);
test<Baz>(map12);
std::cout << "\n*** Done, calling destructors ***" << std::endl;
return 0;
}
@adolfo-rt
Copy link
Author

Expected output:

*** Testing map1 ***
Foo found
Bar found
Baz not found

*** Testing map2 ***
Foo not found
Bar not found
Baz found

*** Testing map12 ***
Foo found
Bar found
Baz found

*** Done, calling destructors ***
Baz destructor
Foo destructor
Bar destructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment