c++ - 如何在 C++ 中对任何函数进行 typedef?

标签 c++ c++11 function-pointers typedef pointer-to-member

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

我们可以typedef一个函数指针,它什么都不获取也不返回,就像这样。

typedef void (*fpointer)();

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

typedef void (*fpointer)(int);

所以我想知道,我可以 typedef 任何函数的指针吗? (非类(class)成员)

感谢大家。

编辑:

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

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

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

    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};};

这是来自 Loki 图书馆。每个函数有 20 个结构。只是我认为它的风格太糟糕了,找到更好的解决方案很有趣。

最佳答案

C++ 中没有一种类型是所有函数类型的父类(super class)型。除了转换回您知道其参数和返回类型的函数类型外,您将如何调用它?

然而,您可以在 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';

}

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

还有另一种选择:您可以不安全地转换任何函数指针 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 };
};

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

关于c++ - 如何在 C++ 中对任何函数进行 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25275472/

相关文章:

c++ - 为什么获取成员函数指针值需要在类内部进行类名限定?

c++ - 如何将位存储到用于文件输入/输出的巨大字符数组

c++ - 使用随机值初始化二维 vector

c++ - 如何使用 auto 声明数组

c++ - std::async 在 Visual Studio 2013 和 2015 之间的不同行为

c - 什么是函数指针?

python - 通过指向该函数的指针获取函数参数值?

c++ - 在Windows中通过串口写入二进制数据

c++ - 可以在 C++14 constexpr 函数中使用 for 循环实例化模板吗?

c++ - 是否可以从同一线程移动分配 std::thread 对象