| description | Learn how to declare and use the static subscript operator in C++. | |||
|---|---|---|---|---|
| title | Static subscript operator (C++) | |||
| ms.date | 08/26/2026 | |||
| ai-usage | ai-assisted | |||
| helpviewer_keywords |
|
In C++23, you can declare the subscript operator, operator[], as a static member function. A static subscript operator doesn't have an implicit object parameter. Use it when a subscript operation doesn't need to access instance data.
Support for this feature was introduced in Visual Studio 2022 version 17.14 (MSVC 14.44). Use the /std:c++latest compiler option.
static return-type operator[](parameter-list);A static subscript operator doesn't have a this pointer. It can't be virtual or have a cv-qualifier (const or volatile) or ref-qualifier (&, &&).
You can call a static subscript operator through an object or by using its qualified name. Taking its address produces a regular function pointer instead of a pointer-to-member function.
The feature-test macro __cpp_multidimensional_subscript has a value of at least 202211L when the static subscript operator is available. Simply checking whether the macro is defined is insufficient because its earlier value of 202110L covers multidimensional subscripting but not static operator[]:
#if defined(__cpp_multidimensional_subscript) && __cpp_multidimensional_subscript >= 202211L
// static subscript operator is available
#endifThe following example defines a stateless type that calculates powers of two and calls its static subscript operator in three ways:
// Compile with: /std:c++latest
#include <iostream>
struct PowersOfTwo
{
static constexpr unsigned int operator[](unsigned int exponent) noexcept
{
return 1U << exponent;
}
};
int main()
{
PowersOfTwo powers_of_two;
std::cout << "powers_of_two[6] = " << powers_of_two[6] << std::endl;
std::cout << "PowersOfTwo::operator[](4) = "
<< PowersOfTwo::operator[](4) << std::endl;
auto power_function = &PowersOfTwo::operator[];
std::cout << "power_function(5) = " << power_function(5) << std::endl;
}powers_of_two[6] = 64
PowersOfTwo::operator[](4) = 16
power_function(5) = 32
Subscripting
Operator overloading
static members
Proposal P2589R1: static operator[]