C++:忽略一行中的多个<<运算符

C++ : Ignoring multiple << Operators in a line

本文关键字:lt 运算符 一行 C++      更新时间:2023-10-16

假设我有以下代码:

int ignored = 0;
StreamIgnore si;
si << "This part" << " should be" << ignored << std::endl;

我希望当这段代码运行时,si将简单地忽略流的其余部分。问题是我希望这是尽可能有效的。一个显而易见的解决方案是:

template <typename T>
StreamIgnore& opertaor<<(const T& val) {
    //Do nothing
    return *this;
}

但是,如果代码类似于:

StreamIgnore si;
si << "Fibonacci(100) = " << fib(100) << std::endl;

然后我必须在//Do Nothing部分之前计算fib(100)。因此,我希望能够完全忽略其余部分,而不需要任何不必要的计算。

为了使这个请求有意义,假设StreamIgnore可以是StreamIgnoreOrNot类,c'tor通过返回*this并使用流,或者new StreamIgnore()实例并忽略其余实例来决定是否忽略流。

我曾想过如何使用Macros,但没能想出一些能让我使用这种语法的东西(即"si << X << Y...")。

如果有人能提出这样做的方法,我将不胜感激。

感谢

我显然会使用IOstreams来禁用/启用相当于设置/清除std::ios_base::failbit的输出。这样做很容易阻止格式化和写入数据。不过,这不会阻止对论点的评估。为此,我会使用逻辑和运算符:

si && si << not_evaluated() << when_not_used();

没有办法做到这一点(不作弊,如下所示)。您的代码只传递了fib(100)的结果,因此根本不能在这里缩短执行时间。

然而,有一个简单的破解方法你可以使用:

template<typename T> struct is_ignored { static const bool yes = false; };
template<> struct is_ignored<StreamIgnore> { static const bool yes = true; };
#define S(x) if(!is_ignored<remove_reference<decltype(x)>::type>::yes) x
S(x) << "meepn";

您可能需要添加一些_Pragma来禁用编译器警告,因为这会导致死代码。