C++ Is it possible to have a generic function pointer?

前端 未结 2 2139
北海茫月
北海茫月 2021-02-20 11:27

In C++ is it possible to make some sort of generic function pointer that points to any function that returns a pointer to some type and takes no arguments?

Eg, one type

2条回答
  •  不思量自难忘°
    2021-02-20 12:16

    The standard does not allow such thing. You may or may not be able to get away with casting your function pointer to void* (*)(). In C++ there are standard-conforming solutions. Here is a simple pre-C++11 one:

    struct MyFunc
    {
      virtual void* operator()() = 0;
      virtual ~Myfunc(){}
    };
    
    template 
    struct MyfuncImpl
    {
      typedef T TFunc();
      MyfuncImpl (TFunc* func) : m_func(func) {}
      void* operator()() { return m_func(); }
     private:
      TFunc* m_func;
    };
    

    Now you can store shared_ptr in your vector.

    A much nicer solution in C++11 could look like this:

    template 
    std::function castToVoidFunc (T* (*func)())
    {
      return [=](){ return func(); };
    }
    

提交回复
热议问题