问题
I'm trying to teach myself some C++17.
Why is the compiler throwing an error for the below code snippet?
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v = { 3, 1, 4 };
std::cout << std::size(v) << '\n';
int a[] = { -5, 10, 15 };
std::cout << std::size(a) << '\n';
}
The compiler throws the following error
manish@Manish-Tummala:~/c_files$ g++ 6.cpp -o - 6.out
6.cpp: In function ‘int main()’:
6.cpp:8:23: error: ‘size’ is not a member of ‘std’
std::cout << std::size(v) << '\n';
^~~~
6.cpp:8:23: note: suggested alternative: ‘size_t’
std::cout << std::size(v) << '\n';
^~~~
size_t
6.cpp:11:23: error: ‘size’ is not a member of ‘std’
std::cout << std::size(a) << '\n';
^~~~
6.cpp:11:23: note: suggested alternative: ‘size_t’
std::cout << std::size(a) << '\n';
^~~~
size_t
回答1:
For C++17 support in GCC, please refer to:
- C++17 Support in GCC
For the time being, C++17 support is not enabled by default:
To enable C++17 support, add the command-line parameter
-std=c++17
to yourg++
command line. Or, to enable GNU extensions in addition to C++17 features, add-std=gnu++17
.
At present, the C++17 ABI for GCC has not been finalized yet. This means that programs built today in C++17 mode may not be able to link against past or future binaries also compiled in C++17 mode (or crash at run time). A stable ABI ensures such interoperability across compiler versions.
Once the ABI is final, afuture version of GCC will enable C++17 mode by default.
回答2:
Your g++ installation needs to be at version 6 or higher. You can check it with
g++ -v
If your g++ version is high enough. You must also execute it with the c++17 command line option.
g++ -std=c++17 6.cpp -o 6.out
or
g++ -std=gnu++17 6.cpp -o 6.out
来源:https://stackoverflow.com/questions/55194309/why-stdsize-is-not-a-member-of-std-in-gcc-8-2-0