Initialize global array of function pointers at either compile-time, or run-time before main()

后端 未结 5 970
甜味超标
甜味超标 2020-12-01 09:04

I\'m trying to initialize a global array of function pointers at compile-time, in either C or C++. Something like this:

module.h

ty         


        
5条回答
  •  温柔的废话
    2020-12-01 09:09

    Since you allow C++, the answer is obviously yes, with templates:

    template int16_t myfunc() { /* N is a const int here */ }
    myfunc_array[] = { myfunc<0>, myfunc<1>, myfunc<2> }
    

    Now, you might wonder if you can create that variable-length initializer list with some macro. The answer is yes, but the macro's needed are ugly. So I'n not going to write them here, but point you to Boost::Preprocessor

    However, do you really need such an array? Do you really need the name myfunc_array[0] for myfunc<0> ? Even if you need a runtime argument (myfunc_array[i]) there are other tricks:

    inline template  int16_t myfunc_wrapper(int i) {
    assert (i : myfunc_wrapper(i-1);
    }
    inline int16_t myfunc_wrapper(int i) { 
      return myfunc_wrapper(i); // NUMBER is defined on with g++ -DNUMBER=N
    }
    

提交回复
热议问题