c++23 introduced static versions of the operator ()
and 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]
// ^^ ^^ <-- Create temporary instances of 'S'?!
std::print("({})[{}]", S()(2, 1), S()[5, 1]); // (3)[4]
// ^^ ^^ <-- Create temporary instances of 'S'?!
return 0;
}
It shocked me that in order to call the static versions of operators ()
and []
an instance of the class is required; I was expecting to be able to call both operators from the type (as other static members) but it is ill formed:
// type --> v v <-- type
std::print("({})[{}]", S(1, 0), S[3, 1]); // (1)[2]
// static operator() -> \____/ \____/ <- static operator[]
But S(1, 0)
looks like a constructor haha, silly me!, it will cause ambiguities if the type S
happens to have a S(int, int)
constructor… but what about S[3, 1]
? This doesn't clash with any in-class entity.
Ok, maybe type(...)
and type[...]
are problematic but what about using the scope operator? unfortunatelly this is ill formed as well:
// type --> v v <-- type
std::print("({})[{}]", S::(1, 0), S::[3, 1]); // (1)[2]
// static operator() -> \____/ \____/ <- static operator[]
I've been reading the p1169r4 and p2589r0 papers and I wasn't able to find any rationale to "force" to instance the type in order to call the static operator ()
or []
nor why the type::(...)
or type::[...]
forms aren't allowed.
Am I missing something?