多维下标运算符(C++23) ​

什么是多维下标运算符 ​

C++23 允许 operator[] 接受多个参数,不再限制为只能接受一个参数。这意味着你可以直接写 matrix[i, j] 来访问二维数组的元素,而不是用 matrix[i][j](链式调用)或 matrix(i, j)(函数调用运算符)来替代。

在 C++20 中,下标表达式中使用逗号运算符已经被废弃(arr[0, 1] 中的逗号以前被当作逗号运算符)。C++23 正式将这个语法赋予了新含义——逗号分隔的多个参数。

cpp
class Matrix {
    int data[3][3];
public:
    // C++23:operator[] 接受多个参数
    int& operator[](int row, int col) {
        return data[row][col];
    }
};

Matrix m;
m[1, 2] = 42;  // 直接用逗号分隔行列

基本示例 ​

cpp
#include <iostream>
#include <vector>
#include <array>
#include <stdexcept>
#include <cstddef>

// ============================
// 示例1:二维矩阵
// ============================

class Matrix {
    std::vector<double> data_;
    std::size_t rows_, cols_;

public:
    Matrix(std::size_t rows, std::size_t cols)
        : data_(rows * cols, 0.0), rows_(rows), cols_(cols) {}

    // C++23 多维下标运算符
    double& operator[](std::size_t row, std::size_t col) {
        return data_[row * cols_ + col];
    }

    const double& operator[](std::size_t row, std::size_t col) const {
        return data_[row * cols_ + col];
    }

    std::size_t rows() const { return rows_; }
    std::size_t cols() const { return cols_; }

    void print() const {
        for (std::size_t i = 0; i < rows_; i++) {
            for (std::size_t j = 0; j < cols_; j++) {
                std::cout << (*this)[i, j] << "\t";
            }
            std::cout << std::endl;
        }
    }
};

void matrix_demo() {
    Matrix m(3, 3);

    // 直接用 [行, 列] 语法
    m[0, 0] = 1.0;  m[0, 1] = 2.0;  m[0, 2] = 3.0;
    m[1, 0] = 4.0;  m[1, 1] = 5.0;  m[1, 2] = 6.0;
    m[2, 0] = 7.0;  m[2, 1] = 8.0;  m[2, 2] = 9.0;

    m.print();
    std::cout << "m[1, 2] = " << m[1, 2] << std::endl;  // 6.0
}

// ============================
// 示例2:三维数组
// ============================

class Array3D {
    std::vector<int> data_;
    std::size_t dim1_, dim2_, dim3_;

public:
    Array3D(std::size_t d1, std::size_t d2, std::size_t d3)
        : data_(d1 * d2 * d3, 0), dim1_(d1), dim2_(d2), dim3_(d3) {}

    // 三个参数的下标运算符
    int& operator[](std::size_t i, std::size_t j, std::size_t k) {
        return data_[(i * dim2_ + j) * dim3_ + k];
    }

    const int& operator[](std::size_t i, std::size_t j, std::size_t k) const {
        return data_[(i * dim2_ + j) * dim3_ + k];
    }
};

void array3d_demo() {
    Array3D arr(2, 3, 4);

    arr[0, 0, 0] = 100;
    arr[1, 2, 3] = 200;

    std::cout << "arr[0,0,0] = " << arr[0, 0, 0] << std::endl;
    std::cout << "arr[1,2,3] = " << arr[1, 2, 3] << std::endl;
}

// ============================
// 示例3:带边界检查
// ============================

class SafeMatrix {
    std::vector<int> data_;
    std::size_t rows_, cols_;

public:
    SafeMatrix(std::size_t rows, std::size_t cols)
        : data_(rows * cols, 0), rows_(rows), cols_(cols) {}

    int& operator[](std::size_t row, std::size_t col) {
        if (row >= rows_ || col >= cols_) {
            throw std::out_of_range("下标越界");
        }
        return data_[row * cols_ + col];
    }

    const int& operator[](std::size_t row, std::size_t col) const {
        if (row >= rows_ || col >= cols_) {
            throw std::out_of_range("下标越界");
        }
        return data_[row * cols_ + col];
    }
};

void safe_demo() {
    SafeMatrix sm(2, 3);
    sm[0, 0] = 10;
    sm[1, 2] = 20;

    std::cout << "sm[0,0] = " << sm[0, 0] << std::endl;
    std::cout << "sm[1,2] = " << sm[1, 2] << std::endl;

    try {
        sm[5, 5] = 99;  // 越界
    } catch (const std::out_of_range& e) {
        std::cout << "异常: " << e.what() << std::endl;
    }
}

// ============================
// 示例4:零参数下标运算符
// ============================

class Singleton {
    int value_ = 42;
public:
    // C++23 允许零参数的 operator[]
    int& operator[]() {
        return value_;
    }
};

void zero_arg_demo() {
    Singleton s;
    std::cout << "s[] = " << s[] << std::endl;
    s[] = 100;
    std::cout << "修改后 s[] = " << s[] << std::endl;
}

// ============================
// 示例5:可变参数下标运算符
// ============================

class FlexArray {
    std::vector<int> data_;
    std::vector<std::size_t> dims_;

    // 计算线性索引
    std::size_t linear_index(std::initializer_list<std::size_t> indices) const {
        std::size_t idx = 0;
        std::size_t stride = 1;
        auto dim_it = dims_.rbegin();
        auto idx_it = std::prev(indices.end());

        for (; dim_it != dims_.rend(); ++dim_it, --idx_it) {
            idx += (*idx_it) * stride;
            stride *= *dim_it;
            if (idx_it == indices.begin()) break;
        }
        return idx;
    }

public:
    FlexArray(std::initializer_list<std::size_t> dims)
        : dims_(dims) {
        std::size_t total = 1;
        for (auto d : dims_) total *= d;
        data_.resize(total, 0);
    }

    // 可变参数模板的下标运算符
    template<typename... Indices>
    int& operator[](Indices... indices) {
        return data_[linear_index({static_cast<std::size_t>(indices)...})];
    }
};

void variadic_demo() {
    FlexArray arr({2, 3, 4});

    arr[0, 0, 0] = 1;
    arr[1, 2, 3] = 999;

    std::cout << "arr[0,0,0] = " << arr[0, 0, 0] << std::endl;
    std::cout << "arr[1,2,3] = " << arr[1, 2, 3] << std::endl;
}

// ============================
// 示例6:对比旧方式
// ============================

// 旧方式1:链式 operator[](返回代理对象)
class OldMatrix {
    int data_[3][3] = {};
public:
    // operator[] 返回行指针
    int* operator[](int row) { return data_[row]; }
};

// 旧方式2:用 operator()
class OldMatrix2 {
    int data_[3][3] = {};
public:
    int& operator()(int row, int col) { return data_[row][col]; }
};

// C++23 方式
class NewMatrix {
    int data_[3][3] = {};
public:
    int& operator[](int row, int col) { return data_[row][col]; }
};

void comparison_demo() {
    OldMatrix old1;
    old1[1][2] = 42;
    std::cout << "旧方式1: old1[1][2] = " << old1[1][2] << std::endl;

    OldMatrix2 old2;
    old2(1, 2) = 42;
    std::cout << "旧方式2: old2(1,2) = " << old2(1, 2) << std::endl;

    NewMatrix m;
    m[1, 2] = 42;
    std::cout << "C++23: m[1,2] = " << m[1, 2] << std::endl;
}

int main() {
    std::cout << "=== 二维矩阵 ===" << std::endl;
    matrix_demo();

    std::cout << "\n=== 三维数组 ===" << std::endl;
    array3d_demo();

    std::cout << "\n=== 边界检查 ===" << std::endl;
    safe_demo();

    std::cout << "\n=== 零参数 ===" << std::endl;
    zero_arg_demo();

    std::cout << "\n=== 可变参数 ===" << std::endl;
    variadic_demo();

    std::cout << "\n=== 对比 ===" << std::endl;
    comparison_demo();

    return 0;
}

三种多维访问方式对比 ​

方式语法标准问题
链式 [][]m[i][j]所有版本需要代理对象或返回指针
函数调用 ()m(i, j)所有版本语义不够直观
多维 []m[i, j]C++23旧代码中逗号运算符语义不同

适用场景 ​

  • 二维/三维矩阵类
  • 多维数组容器
  • 图像像素访问(row, col)
  • 空间数据结构(x, y, z)
  • 与 std::mdspan 配合使用

常见问题 ​

现有的 std::vector 和 std::array 支持多维下标吗?

不支持。C++23 的多维下标运算符只对新类型有效。现有标准库容器的 operator[] 仍然只接受一个参数。要使用多维下标,需要自定义类或使用 std::mdspan。

m[0, 1] 在 C++17 和 C++23 中的含义不同?

是的。在 C++17 中,m[0, 1] 中的逗号是逗号运算符,等价于 m[1]。C++20 废弃了这种用法。C++23 中,如果 operator[] 定义了多参数版本,m[0, 1] 就是传两个参数。

可以同时定义单参数和多参数的 operator[] 吗?

可以。它们是不同的重载,编译器根据参数数量选择。

注意事项 ​

  • C++23 特性
  • 只对用户自定义类型有效,不改变现有标准库容器
  • C++20 已废弃下标表达式中的逗号运算符
  • 可以和 const 重载配合使用
  • 支持零参数和可变参数模板
  • std::mdspan 是标准库中使用多维下标的代表

总结 ​

C++23 的多维下标运算符允许 operator[] 接受多个参数,使得 m[i, j] 这样的语法成为可能。这解决了长期以来多维容器访问语法不够直观的问题——不再需要链式 [][](需要代理对象)或用 () 替代(语义不明确)。这个特性只影响用户自定义类型,现有标准库容器不受影响。典型应用场景包括矩阵、三维数组、图像容器等。标准库中的 std::mdspan 就是利用这个特性的代表。