可以,但要注意 auto pa = {f1, f2, f3}; 并不是在定义一个函数指针数组,而是定义了一个
std::initializer_list<…> —— 元素类型正是这些函数指针的类型。
1. 示例代码
#include <iostream>
#include <type_traits>
#include <initializer_list>
const double* f1(const double* a, int n) { return a; }
const double* f2(const double* a, int n) { return a + 1; }
const double* f3(const double* a, int n) { return a + 2; }
int main() {
// f1/f2/f3 都是“接受 (const double*,int) 返回 const double*”的函数
// auto pa 会被推断为:
// std::initializer_list<const double* (*)(const double*,int)>
auto pa = { f1, f2, f3 };
// 验证类型
using FuncPtr = const double* (*)(const double*,int);
static_assert(std::is_same<
decltype(pa),
std::initializer_list<FuncPtr>
>::value, "类型不一致");
std::cout << "pa.size() = " << pa.size() << "\n"; // 输出 3
// 访问第 i 个函数指针必须用迭代器或 std::next
auto it = pa.begin();
FuncPtr p0 = *it; // f1
std::cout << "调用第 1 个函数:" << (p0(nullptr,0)==nullptr) << "\n";
FuncPtr p2 = *std::next(pa.begin(), 2); // f3
std::cout << "调用第 3 个函数:" << (p2(nullptr,0)==nullptr) << "\n";
return 0;
}
编译并运行,这段代码会正常通过 static_assert,并打印出
pa.size() = 3
调用第 1 个函数:1
调用第 3 个函数:1
2. 注意事项
- auto pa = { … }
‐‐ 会推断成 std::initializer_list<T>,其中 T 是各个元素的公有类型(此处就是 const double* (*)(const double*,int))。
initializer_list 只能读不能写,没有下标操作符 operator[],要访问元素得用迭代器。
- 如果你 真的需要 原生的函数指针数组(可下标、可修改),就不能用
auto pa = {…},而要显式写出类型或用 std::array:
// 方案 A:显式数组
const double* (* pa_arr[3])(const double*,int) = {f1,f2,f3};
// 方案 B:std::array(C++11+)
#include <array>
std::array<FuncPtr,3> pa_arr2 = {f1,f2,f3};
// 方案 C:C++17类模板参数推导
std::array pa_arr3 = {f1,f2,f3}; // 推断成 std::array<FuncPtr,3>
3. 小结
- 能否写?
是的,auto pa = {f1,f2,f3}; 在 C++11/14/17 都合法。
- 结果是什么?
pa 的类型是 std::initializer_list<const double* (*)(const double*,int)>,不是原生数组。
- 如果需要原生数组?
请显式写出数组类型或改用 std::array。