Example
struct s {
static constexpr auto operator[]() { return 42; }
};
static_assert(42 == s{}[]);
static_assert(42 == s::operator[]());
Puzzle
- Can you provide an example which shows that
static operator[]
requies less assembly instructions thannon-static
version?
Solutions
struct foo {
static auto operator[]() -> int;
};
struct bar {
auto operator[]() const -> int;
};
auto get(const int, const foo &o) { return o[]; }
auto get(const int, const bar &o) { return o[]; }
struct X { static void operator[](); };
struct Y { void operator[]() const; };
auto fn1() { X{}[]; }
auto fn2() { Y{}[]; }
struct s {
static constexpr auto operator[]() { return 42; }
};
static_assert(42 == s{}[]);
static_assert(42 == s::operator[]());
struct ns {
constexpr auto operator[](){ return 42; }
};
static_assert(42 == ns{}[]);
int main() {
s{}[];
ns{}[];
};
struct foo {
static auto operator[]() -> int;
};
struct bar {
auto operator[]() const -> int;
};
template<typename ...Ts>
struct getter
{
int operator()() const
{
return std::apply([](Ts const &... args ){ return (args[] +...);},t);
}
std::tuple<Ts...> t;
};
int get(getter<foo,foo,foo,foo,foo> const & g){ return g();}
int get(getter<bar,bar,bar,bar,bar> const & g){ return g();}
// static version
struct s {
static constexpr auto operator[](int i) { return 42; }
};
int main(){
return s::operator[](0);
}
// static version
struct s {
static void operator[]();
};
auto fn(){
s::operator[]();
}