Consider having a simple class, that writes integers to cout
depending on its state:
#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;
};
Consider now I have a COMPILE-TIME constant number of toggles (i.e. calls to NotAWriter.toggle()
).
I want a program to choose whether to print or not depending on the variable on
in compile-time, something like this:
NotAWriter& operator<<(const int& arg) {
if constexpr (on) std::cout << arg;
return *this;
}
or 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;}
However the usage of this
in constant expressions is prohibited:
error: use of ‘this’ in a constant expression
| if constexpr (on) std::cout << arg;
| ^~
Is there a way to do this (choose overload or if-branch) depending on a member-variable at compile-time? If I sure the number of variable changes is compile-time constant, of course.