gpt4 book ai didi

c++ - 我可以在编译时强制执行此运算符调用计数要求吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:19 26 4
gpt4 key购买 nike

我有一个类,在接口(interface)方面,就这么简单:

struct Foo
{
inline Foo & operator << (int i)
{
return *this;
}
};

然后我可以按以下方式使用它:

Foo foo;
foo << 1 << 2 << 3 << 4;

现在我想限制这个运算符的使用。 例如,我希望它在序列点之间被调用偶数次。

我目前使用内部代理类来解决这个问题。创建一个临时对象,在控制序列的末尾销毁它并检查该运算符被调用了多少次:

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);
}

有一些注意事项,但它主要起到了作用:

Foo foo;
foo << 1 << 2 << 3 << 4; /* is OK */
foo << 1 << 2 << 3; /* triggers an assert */

现在我想知道是否有一种方法可以在编译时强制执行此操作,或者使用相同的代理技术,或者使用其他策略。

我想实现的另一个例子:在将任意数量的 float 传递给运算符后强制推送至少一个 int:

foo << 1 << 2 << 3.f << 4.f << 5; /* is OK */
foo << 1 << 2 << 3.f << 4.f; /* illegal because one `int` is needed */

最佳答案

为什么不使用像 FooPair 这样的东西来强制均匀性:

struct FooPair
{
int m_x, m_y;

FooPair(int x, int) : m_x(x), m_y(y)
{
}
};

和:

inline Foo & operator << (const FooPair &pair)
{
return *this;
}

所以人们不得不称它为:

Foo foo;
foo << FooPair(1,2) << FooPair(3,4);

它更冗长,但会确保传递偶数个值。

关于c++ - 我可以在编译时强制执行此运算符调用计数要求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17808436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com