为什么以下代码无法在 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/