I have a class that is simple on the interface like this:
struct Foo { inline Foo & operator << (int i) { return *this; } };
Then I can use it as follows:
Foo foo; foo << 1 << 2 << 3 << 4;
Now I would like to limit the use of this operator. For example , I would like it to be called an even number of times between points in a sequence.
I am currently addressing this issue using the inner proxy class. A temporary structure is created, which is destroyed at the end of the control sequence and checks how many times the 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 are a few caveats, but basically this does the job:
Foo foo; foo << 1 << 2 << 3 << 4; foo << 1 << 2 << 3;
Now I'm wondering if there is a way to ensure this at compile time, either using the same proxy technology or using a different strategy.
Another example of what I would like to achieve: forcing at least one int after any float been passed to the operator:
foo << 1 << 2 << 3.f << 4.f << 5; foo << 1 << 2 << 3.f << 4.f;
source share