How to create a container of functions?

Hi,

I need a container of functions (like a vector for example). But each function may be different than the others although they all return the string type. They differ in the parameter type, like so:


1
2
3
std::string to_string(int value)
std::string to_string(double value)
// etc... 


These functions are meant to format the value into a table cell as text. It might be necessary to specify formatting flags as well.

Any ideas?

Regards,
Juan Dent
Normally an array of functions require the same type and number of parameters.

Why can't you just use "normal" C++ overload mechanisms? For example your above snippet should just used as normal overloads.

But be careful there is already a standard function called to_string(), and using the prefix "to_" should be avoided when possible as there are quite a few standard functions that start with this prefix.

Hi,

Not sure if this will work for you:

https://stackoverflow.com/questions/37904897/a-container-of-stdfunction-with-polymorphic-types-as-function-arguments

Basically it's a std::unordered_map of std::unique_ptr to std::function

IIRC std::function can be any callable target

Good Luck !! :+)
One can work with entire overload sets by having a function object with an overloaded operator()():
For example:
1
2
3
4
5
6
7
8
9
10
constexpr struct my_to_string_t 
{
  std::string operator()(int x) const { return std::to_string(x); } ;
  std::string operator()(double x) const { return std::to_string(x); };
  // ...
} my_to_string;

// ...
my_to_string(2.0);
my_to_string(42);


If the collection really needs to be modifiable at run-time, then I think you have to use some trickery like @TheIdeasMan suggests.
Last edited on
Thanks for the ideas!!
Topic archived. No new replies allowed.