c++ - 使用指向函数的指针和以默认值作为参数的 vector 的函数会导致编译错误

标签 c++ visual-c++ function-pointers initializer-list default-arguments

为什么以下代码无法在 MSVC 上编译

#include <vector>

void func(double (* fptr)(double), const std::vector<double> & v = {})
{
}

我收到以下错误。

source_file.cpp(6): error C2065: 'fptr': undeclared identifier

source_file.cpp(6): error C2062: type 'double' unexpected

source_file.cpp(6): error C2143: syntax error: missing ';' before '{'

source_file.cpp(6): error C2143: syntax error: missing ')' before ';'

source_file.cpp(6): error C2447: '{': missing function header (old-style formal list?)

source_file.cpp(6): error C2059: syntax error: ')'

source_file.cpp(7): error C2447: '{': missing function header (old-style formal list?)

Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64

当我删除任一 - vector 默认值时:

void func(double (* fptr)(double), const std::vector<double> & v)

或函数指针:

void func(const std::vector<double> & v = {})

错误消失。这是 MSVC 的错误还是我遗漏了什么?

Clang和G++的代码没有问题。

您可以使用以下命令查看代码 https://rextester.com/l/cpp_online_compiler_visual

最佳答案

Is it some MSVC bug or am I missing something?

你什么都不会错过。这是一个 MSVC 错误。您可以通过重载来解决它:

void func(double (* fptr)(double), const std::vector<double> & v)
{
}

void func(double (* fptr)(double)) {
    std::vector<double> v;
    func(fptr, v); // or just func(fptr, {})
}

但值得注意的是,获取 func 的地址现在是不明确的,这与原始的、完全符合标准的代码不同。

关于c++ - 使用指向函数的指针和以默认值作为参数的 vector 的函数会导致编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310552/

相关文章:

c# - 带有函数参数的重载函数的奇怪模糊调用

c++ - 在 C++ 中定义 Unicode 时映射格式说明符?

C++ 命名空间问题

c++ - Windows 上的静态链接 OpenGL 库

visual-c++ - DLL 的 "image version"有何用途(使用/VERSION Visual C++ 链接器开关设置)?

c - 当调用函数时,当两者都采用指针类型参数时,为什么我们在某个地方需要 & 而在另一个地方不需要 & ?

android - 如何将 .cpp 包含文件添加到 android.mk 中的依赖项?

c++ - 无法更改位于另一个窗口内的窗口的背景颜色

c++ - 在 Metro 应用程序中使用 fopen 打开文件

c - 二叉搜索树 (BST) - 遍历搜索