C++ how do I store any value in a map

github logo ・1 min read

I am writing an emscripten compiled web assembly project to get Lua working alongside node, this is working out very nicely because I can get values from Lua back into CPP. I have bootstraped a node.js clone module system so this means I will always get a module.exports table back. What I'd love to know is how can I iterate over this table and convert it to a cpp map to return to JavaScript. I'm using c++17 I think...

Anyways hope any inspirational ideas can help. Much wow and thanks.

twitter logo DISCUSS (3)
markdown guide

In general, you need sum type (tagged union, etc. -- it has many names).
In C++ there is no built-in ST, but there are std::any and std::variant (second is better, I think). Both of them can be found at cppreference.com


Thank you, Andrew that's good to know, I have spotted both types but couldn't get it to compile std::any or std::variant. Might have to look into CPP supported versions for emscripten.


If you can include typeinfo, it's not so hard to implement class like Any by yourself
If you're familiar with C++ variadic templates (who knows), you can make Variant by yourself
If you don't manage to include standart Any or Variant, and you need sum type with fixed number of hidden (I don't know how to call them) types you can make template Variant class (it will be pretty ugly, but it'll work, hehe)

Classic DEV Post from Feb 10

Is Haskell bad for FP?

After reading a few frustrated posts from people trying to learn FP through Has...

Adam Crockett profile image
I work at Dyson as a Front end focused Full stack developer, I play with all sorts really. Lately WASM is my toy of interest.

Read more long-form software content.

Sign up (for free)

Become a better software developer.