C++ 中的函数和函数指针

Functions and function pointers in C++

参考以下代码

#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;

void function() {
    cout << "Hello World" << endl;
}

int main() {
    vector<void (*) ()> functions;
    functions.push_back(function);         // (1) no error
    functions.push_back(&function);        // (2) no error
    for (const auto& func : functions) {
        func();
    }

    // vector<decltype(function)> vec;     // (3) error
    return 0;
}

我取消注释(3)时似乎有错误,我只是想了解这背后的原因。当我将函数作为参数传递给模板化函数时,它会将类型解析为函数指针吗?编译器将所有函数类型推导为函数指针是有意义的,但为什么 decltype() 不解析为函数指针?

decltype(function)void() - 一个函数。
您需要的是函数的衰减版本 - void(*)():

std::decay<decltype(function)>::type

std::vector < std::decay<decltype(function)>::type > myPtrFunctionVec;

PS.
如果你正在使用 VC++ (visual stdio),你可以通过打印 typeid(decltype(XXX)).name() 轻松地看到从 decltype 推导出的类型。 VC++ 与其他编译器不同,给出类型的未修饰名称。元编程调试非常方便。

编辑:
正如@Daniel Jour 评论的那样,解决方案 decltype(&function) 也有效,因为构造 &f 给出了指向 f 的指针,这正是您需要的