考虑有一个简单的类,根据其状态将整数写入
cout
:
#include <iostream>
class NotAWriter{
public:
NotAWriter& operator<<(const int& arg) {
if (on) std::cout << arg;
return *this;
}
void toggle() {on=!on;}
private:
bool on = false;
};
现在考虑一下我有一个编译时恒定数量的切换(即调用
NotAWriter.toggle()
)。
我希望程序根据编译时的变量
on
来选择是否打印,如下所示:
NotAWriter& operator<<(const int& arg) {
if constexpr (on) std::cout << arg;
return *this;
}
或者这个
std::enable_if<on, NotAWriter&> operator<<(const int& arg) {
std::cout << arg;
return *this;
}
std::enable_if<!on, NotAWriter&> operator<<(const int& arg) {return *this;}
但是,禁止在常量表达式中使用
this
:
error: use of ‘this’ in a constant expression
| if constexpr (on) std::cout << arg;
| ^~
有没有办法根据编译时的成员变量来做到这一点(选择重载或 if 分支)?当然,如果我确定变量更改的数量是编译时常数。
您是否有理由不能依赖这样或类似的东西:
#include <iostream>
template <bool on>
class NotAWriter
{
public:
NotAWriter& operator<<(const int& arg)
{
if constexpr (on)
std::cout << arg;
return *this;
}
};
int main()
{
NotAWriter<false>() << 4;
NotAWriter<true>() << 4;
return 0;
}