I've been screwing around with templates lately, and I'm attempting to figure out why the following won't compile:
struct value { int a; const auto opBinary(string op, T)(in T rhs) const pure { static if (op == "+") return intermediateValue!(value.plus,this,rhs)(); } ref value opAssign(T)( in T t ) { a = t.a; return this; } static int plus(T1, T2)(in T1 x, in T2 y) pure { return x.a + y.a; } } struct intermediateValue(alias Op, alias A, alias B) { auto opBinary(string op, T)(in T rhs) const pure { static if (op == "+") return intermediateValue!(value.plus,this,rhs)(); } @property auto a() const pure { return Op(A, B); } } void main() { value a = value(2); value b = value(3); value c; c = a + b; } The error is: d_playground.d(34): Error: pure nested function 'a' cannot access mutable data 'this' d_playground.d(34): Error: pure nested function 'a' cannot access mutable data 'this' d_playground.d(10): Error: template instance d_playground.value.opBinary!("+", value).opBinary.intermediateValue!(plus, this, rhs) error instantiating d_playground.d(44): instantiated from here: opBinary!("+", value) d_playground.d(44): Error: template instance d_playground.value.opBinary!("+", value) error instantiating What is going on? Why is 'a' not allowed to "access" mutable data (even though it isn't modifying it)? How do I tell the compiler to pass "this" in a const fashion?