Using std::size

I have found that many still have issue using std::size() general template function.

As mentioned on C++ reference, std::size was implemented in C++17.

Now, the difference comes with the compiler used when using the said implementation.

Assume following example.

#include <iostream>
 
int main()
{
    int numbers[] = {10, 20, 30, 40, 50};
    
    std::cout << std::size(numbers);
    
    return 0;
}

The example works on C++17 (GCC) and newer versions (C++20)).

But it does not work on C++17 (Clang) or older versions of GCC (C++14).

So know the compiler that you are using.

Change compiler in Visual Studio
Change compiler in CLion
Change compiler in Code::Blocks
Change compiler in Visual Studio Code

1 Like

Thank you for this post! I got it working on macOS in VS Code and in CLion.

Just a few notes for macOS using Clang:

In CLion I had to

  • set the compiler to /usr/bin/clang++
  • add –std c++20 to the compiler options under Run/Debug Configurations
  • set(CMAKE_CXX_STANDARD 20)

In VSCode I had

  • set C++ Standard to c++20 in C/C++ Edit Configurations (command pallet)
  • set Cpp Standard to c++20 in the settings of the C/C++ Extension
  • make sure to use clang++ compiler under Tasks: Configure Default Build Task
  • add these two lines to tasks.json under args:
    • β€œβ€“std”,
    • β€œc++20”,