I need help getting the broken part of this code working.
How do I tag dispatch two functions (that return different value-types) based on a string?
If the overall code can be simplified with the intent of dispatching with strings, please do make recommendations. TY.
Requirements:
- Dispatch based on a string
- Rectangle overload needs to return int, while Circle overload needs to return std::string
- The mapping from Rectangle_Type to int and Circle_Type to std::string is fixed and known at compile time. Part of my problem is std::map is a run-time construct: I don't know how to make the std::string to tag mapping a compile-time construct.
- If necessary, run-time resolution is okay: however, the dispatch must allow for different return types based on the enum/type resolved to.
CODE
#include <map>
#include <string>
#include <iostream>
struct Shape { };
struct Rectangle_Type : public Shape { using value_type=int; };
struct Circle_Type : public Shape { using value_type=std::string; };
Rectangle_Type Rectangle;
Circle_Type Circle;
static std::map<std::string,Shape*> g_mapping =
{
{ "Rectangle", &Rectangle },
{ "Circle", &Circle }
};
int tag_dispatch( Rectangle_Type )
{
return 42;
}
std::string tag_dispatch( Circle_Type )
{
return "foo";
}
int
main()
{
std::cerr << tag_dispatch( Circle ) << std::endl; // OK
std::cerr << tag_dispatch( Rectangle ) << std::endl; // OK
#define BROKEN
#ifdef BROKEN
std::cerr << tag_dispatch( (*g_mapping["Rectangle"]) ) << std::endl;
std::cerr << tag_dispatch( (*g_mapping["Circle"]) ) << std::endl;
#endif
}