如何在c ++中使用任何函数的typedef?

use*_*337 0 c++ typedef member-function-pointers function-pointers c++11

我想我想要一些不可能的东西,但至少我可以问))

我们可以输入一个函数的指针,它什么都没有,并且没有返回这样的东西.

typedef void (*fpointer)();
Run Code Online (Sandbox Code Playgroud)

如果函数得到一个int,那么

typedef void (*fpointer)(int);
Run Code Online (Sandbox Code Playgroud)

所以我想知道,我可以输入任何函数的指针吗?(非集体成员)

谢谢大家.

编辑:

    template <typename T>
    struct IsMemberFunctionPointerRaw
    {enum{result = 0};};

    template <typename T, typename S>
    struct IsMemberFunctionPointerRaw<T (S::*)()> 
    {enum {result = 1};};
Run Code Online (Sandbox Code Playgroud)

...........................................

    template <typename T, typename S, 
        typename P01, typename P02, typename P03, typename P04, typename P05,
        typename P06, typename P07, typename P08, typename P09, typename P10,
        typename P11, typename P12, typename P13, typename P14, typename P15,
        typename P16, typename P17, typename P18, typename P19, typename P20>
    struct IsMemberFunctionPointerRaw<T (S::*)(
        P01, P02, P03, P04, P05, 
        P06, P07, P08, P09, P10, 
        P11, P12, P13, P14, P15,
        P16, P17, P18, P19, P20)> 
    {enum {result = 1};};
Run Code Online (Sandbox Code Playgroud)

这是来自Loki图书馆.每个功能都有20个结构.只是我认为它的风格太糟糕了,找到更好的解决方案很有意思.

Jon*_*rdy 7

C++中没有类型是所有函数类型的超类型.除了通过转换回你知道参数和返回类型的函数类型之外,你会如何调用它?

但是,您可以在std::function类型中存储任何函数指针或函子,只要它们具有相同的签名:

#include <functional>
#include <iostream>

// Actual function
int add1(int x) { return x + 1; }

// Functor (callable object)
struct Add {
  Add(int y) : y(y) {}
  int operator()(int x) { return x + y; }
  int y;
};

int main() {

  std::function<int(int)> g = add1;
  std::cout << g(2) << '\n';

  g = Add(2);
  std::cout << g(3) << '\n';

  int z = 3;
  g = [z](int x) { return x + z; };
  std::cout << g(4) << '\n';

}
Run Code Online (Sandbox Code Playgroud)

这是将C++ 11 lambdas传递给函数的一种方法,它们与实际(实现定义的)类型无关.

还有另一种选择:您可以使用不安全地将任何函数指针强制转换p为另一种函数类型reinterpret_cast<void(*)()>(p).但是,在调用之前,必须将其强制转换为原始类型.从技术上讲,您不能简单地使用,reinterpret_cast<void*>(p)因为不能保证对象指针类型和函数指针类型具有相同的大小,但实际上它们在所有常见体系结构中都是相同的.

如果您只是想要一个特征来确定给定的函数指针类型是否是成员函数指针,那么您可以使用可变参数模板来匹配任意数量的参数类型:

template<typename T>
struct IsMemberFunctionPointerRaw {
  enum { value = 0 };
};

template<typename Result, typename Class, typename... Args>
struct IsMemberFunctionPointerRaw<Result (Class::*)(Args...)> {
  enum { value = 1 };
};
Run Code Online (Sandbox Code Playgroud)

这在C++ 11中编纂为std::is_member_function_pointer.