c++ - std::function 如何知道调用约定?

标签 c++ c++11 calling-convention

int __cdecl ccall(int i)
{
    wprintf(L"ccall(%d)", i);
    return 0;
}

int __stdcall stdcall(int i)
{
    wprintf(L"stdcall(%d)", i);
    return 0;
}

int __cdecl wmain(int argc, wchar_t **argv)
{
    std::function<int(int)> fnc = ccall;
    std::function<int(int)> fnstd = stdcall;

    fnc(10); // printed well
    fnstd(100); // printed well
    return 0;
}

我担心如何将 __stdcall 函数 分配给 std::function 对象。 但是没有任何指定的调用约定,它看起来工作正常。 std::function 怎么知道调用约定是什么?

最佳答案

std::function 能够存储使用任何调用约定的函数指针。

§ 20.8.11.2:

The function class template provides polymorphic wrappers that generalize the notion of a function pointer. Wrappers can store, copy, and call arbitrary callable objects (20.8.1), given a call signature (20.8.1), allowing functions to be first-class objects.

作为John Calsbeek added : 标准中没有关于调用约定的特别内容,但编译器正在执行它们的工作,函数指针包含有关约定的信息。

对于函数指针,您需要指定不寻常的调用约定:

typedef int(* c_ptr_t)(int);
typedef int(__stdcall * std_ptr_t)(int);

c_ptr_t c_ptr = ccall;
std_ptr_t std_ptr = stdcall;

// But std::function doesn't mind:
std::function<int(int)> fnc = c_ptr;
std::function<int(int)> fnstd = std_ptr;

关于c++ - std::function 如何知道调用约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10170087/

相关文章:

C++11 在运行时索引模板参数包以访问第 N 类型

c++ - 使用输入参数初始化结构

调用约定错误 - C

C++程序读取txt文件并对数据进行排序

c++ - 为什么我的 C++ 对象不能影响另一个 C++ 对象?

c++ - 如何在输出中获取具有 'i'(虚数值)的复数输出

assembly - 为什么使用向量寄存器而不是将标准参数保存在堆栈中?

c++ - 具有自动存储持续时间的虚拟功能似乎不起作用

c++ - 如何 SFINAE 输出非容器参数

c - 有没有办法在进入功能之前保存寄存器?