You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++23中为何调用static operator()和[]必须依赖类实例?

C++23静态operator()与operator[]的调用困惑

C++23引入了static版本的operator ()和operator [],示例代码如下:

#include <iostream>
#include <format>

struct S
{
    static int operator()(int a, int b) { return a + b; }
    static int operator[](int a, int b) { return a - b; }
};

int main()
{
    std::print("({})[{}]", S{}(1, 0), S{}[3, 1]); // (1)[2]
//                          ^^         ^^ <-- 创建S的临时实例?!
    std::print("({})[{}]", S()(2, 1), S()[5, 1]); // (3)[4]
//                          ^^         ^^ <-- 创建S的临时实例?!
    return 0;
}

令人困惑的是,调用这些static版本的运算符必须依赖类的实例;原本期望能像调用其他静态成员一样直接通过类型调用,但以下写法均非法:

//            type --> v        v <-- type
std::print("({})[{}]", S(1, 0), S[3, 1]); // (1)[2]
// static operator() -> \____/   \____/ <- static operator[]

虽然S(1, 0)会和S(int, int)构造函数产生歧义,但S[3, 1]并不会与类内任何实体冲突。尝试使用作用域运算符的写法同样非法:

//            type --> v          v <-- type
std::print("({})[{}]", S::(1, 0), S::[3, 1]); // (1)[2]
//   static operator() -> \____/     \____/ <- static operator[]

查阅p1169r4和p2589r0提案后,未找到强制要求通过实例调用这些静态运算符的理由,也未找到禁止type::(...)或type::[...]写法的原因,请问是否遗漏了相关细节?


内容的提问来源于stack exchange,提问作者PaperBirdMaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:07:31