C++:忽略一行中的多个<<运算符
C++ : Ignoring multiple << Operators in a line
假设我有以下代码:
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
来禁用编译器警告,因为这会导致死代码。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多