c++ - Can I enforce this operator call count requirement at compile time? -
i have class which, interface-wise, simple this:
struct foo { inline foo & operator << (int i) { return *this; } };
i can use in following way:
foo foo; foo << 1 << 2 << 3 << 4;
now restrict usage of operator. for instance, called number of times between sequence points.
i address problem using internal proxy class. temporary created which, @ end of control sequence, destroyed , checks how many times operator has been called:
struct foo { inline foo() : m_count(0) {} private: struct fooproxy { friend struct foo; inline ~fooproxy(); inline struct foo & operator << (int i); private: inline fooproxy(struct foo &foo) : m_foo(foo) {} struct foo &m_foo; }; public: inline fooproxy operator << (int i); private: int m_count; }; inline foo::fooproxy foo::operator << (int i) { ++m_count; return fooproxy(*this); } inline foo & foo::fooproxy::operator << (int i) { ++m_foo.m_count; return m_foo; } inline foo::fooproxy::~fooproxy() { assert(m_foo.m_count % 2 == 0); }
there few caveats job:
foo foo; foo << 1 << 2 << 3 << 4; /* ok */ foo << 1 << 2 << 3; /* triggers assert */
now wondering whether there way enforce @ compile time, either using same proxy technique, or using strategy.
another example of achieve: enforce pushing @ least 1 int
after number of float
have been passed operator:
foo << 1 << 2 << 3.f << 4.f << 5; /* ok */ foo << 1 << 2 << 3.f << 4.f; /* illegal because 1 `int` needed */
you use template proxy encode state it's template parameter rather member.
however unless use eventual return value something, can check conditions, not others. example may check int inserted before float or no 2 floats inserted in row, can't check whether int inserted after floats.
generally may detect condition must satisfied before next insert specializing insertion operator invalid invalid states. can't check final state, because proxies must destructible (each different, intermediate ones destroyed).
Comments
Post a Comment