Question

Is there any solution to run a function/macro that name is created by concatenation of two strings?

I just want to do something like that:

template <char *A, char *B, int C> 
int function_that_run_other_function(void){

    // Here is the main point
    char function_name[80];
    strcpy (function_name, "function");
    strcat (function_name, A);
    strcat (function_name, B);
    return function_name(C);

}

I can do this using macro:

#define macro_that_run_function(A,B,C) \
    function_##A##B##(C);

But I don't want to use macro because of many problems with macros. Is it possible to do in C++ without any additional libraries?

Was it helpful?

Solution

I got curious and after a little while I ended up with this ungodly mess and general mainentace nightmare:

main.cpp:

#include <map>
#include <iostream>
#include <sstream>
#include <functional>
#include <cstring>

typedef std::function<void(int)> func;
typedef std::map<std::string, func> FuncMap;

template <char* A, char* B, int C>
void runner(FuncMap funcs){
    std::stringstream ss;
    ss <<A <<B;
    return funcs[ss.str()](C);
}

void ABC(int val) {
    std::cout <<"Woo: " <<val <<"\n";
}

extern char a[]; //due to external linkage requirement
extern char b[];

int main(...) {
    FuncMap funcs;
    strcpy(a, "A");
    strcpy(b, "B");
    funcs["AB"] = std::bind(&ABC, std::placeholders::_1);
    runner<a, b, 0>(funcs);
    return 0;
}

vars.cpp:

char a[5] = {""};
char b[5] = {""};

So yes with enough force you can make c++ do something along the lines of what you want, but I really wouldn't recommend it.

OTHER TIPS

No, C++ does not allow the compile or run time manipulation or inspection of symbol names (barring the implementation specified type info stuff).

Dynamic libraries often export names (mangled for C++, almost unmangled for `extern "C"``), and libraries for loading them usually (always?) allow them to be loaded by string value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top