D
Derek
I came upon the idea of writting a logging class that
uses a Python-ish syntax that's easy on the eyes (IMO):
int x = 1;
double y = 2.5;
std::string z = "result";
debug = "Results:", x, y, z;
The above example outputs:
Results: 1 2.5 result
The implementation uses a template comma operator and a
template operator= to kick things off. Here is a very
minimal implementation:
struct Value
{
template<typename T>
Value(const T& x)
{ std::cout << x << ' '; }
template<typename U>
Value operator,(const U& y)
{ return Value(y); }
};
struct Log{
template<typename T>
Value operator=(const T& x)
{ return Value(x); }
} debug;
It works, but now that I think about it, I'm not sure
WHY it works. Does it work because the operator= has
higher precedence than the comma operator, so the
compiler sees it like this:
(debug = "Results:"), x, y, z;
Of course operator= returns a Value object which
displays "Result" and (thanks to the template comma
operator) keeps the chain going in the normal
left-to-right evaluation order?
If this is the case, then I find it counter-intuitive
because the type and value of an expression in the form
(e1,e2) is e2. I find this behavior a bit surprising
and inconsistent:
void print(int i)
{ std::cout << i << '\n'; };
int w;
w = 1, 2; // w = 1
print(w); // prints 1
print((1,2)); // prints 2
uses a Python-ish syntax that's easy on the eyes (IMO):
int x = 1;
double y = 2.5;
std::string z = "result";
debug = "Results:", x, y, z;
The above example outputs:
Results: 1 2.5 result
The implementation uses a template comma operator and a
template operator= to kick things off. Here is a very
minimal implementation:
struct Value
{
template<typename T>
Value(const T& x)
{ std::cout << x << ' '; }
template<typename U>
Value operator,(const U& y)
{ return Value(y); }
};
struct Log{
template<typename T>
Value operator=(const T& x)
{ return Value(x); }
} debug;
It works, but now that I think about it, I'm not sure
WHY it works. Does it work because the operator= has
higher precedence than the comma operator, so the
compiler sees it like this:
(debug = "Results:"), x, y, z;
Of course operator= returns a Value object which
displays "Result" and (thanks to the template comma
operator) keeps the chain going in the normal
left-to-right evaluation order?
If this is the case, then I find it counter-intuitive
because the type and value of an expression in the form
(e1,e2) is e2. I find this behavior a bit surprising
and inconsistent:
void print(int i)
{ std::cout << i << '\n'; };
int w;
w = 1, 2; // w = 1
print(w); // prints 1
print((1,2)); // prints 2