问题
Please considere the following code-snippet:
#include <iostream>
void print(auto arg) {
std::cout << arg << std::endl;
}
int main() {
print("Hi");
return 0;
}
As you can see here (https://godbolt.org/z/2GSrXs) using GCC the code compiles and runs fine.
As you can see here (https://godbolt.org/z/rtR6w9) using Visual C++ the code does not compile and results in the error message:
<source>(3): error C3533: a parameter cannot have a type that contains 'auto'
.
It seems to me that this feature has not jet been implementet in Visual C++? Additionally I was not able to find the compiler feature in the following list: https://docs.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance?view=vs-2019. So I am not sure if the Microsoft developer have the feature on their ToDo List?
回答1:
Functions receiving auto is a C++20 feature. It must be enabled with /std:latest
. However, MSVC only has partial support for this syntax at this time, so not all declaration using this feature will work.
GCC has supported auto in function parameters since early C++14 days as an extension.
You can read more about this C++20 feature reading P1141R2: Yet another approach for constrained declarations
回答2:
Remaining in C++14 standard, you can use the following lambda instead of your function:
auto print = [](auto arg) {
std::cout << arg << std::endl;
};
来源:https://stackoverflow.com/questions/62516242/function-with-auto-parameter-compiles-using-gcc-but-does-not-compile-using-visua