V Tue, 30 Dec 2014 13:17:08 +0000 Claude via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> napsáno:
> Hello, I'm trying to use templates to define several methods > (property setters) within a class to avoid some code duplication. > Here is an attempt: > > class Camera > { > private: > Vector4 m_pos; > float m_fov, m_ratio, m_near, m_far; > bool m_matrixCalculated; > > public: > void SetProperty(Tin, alias Field)(ref Tin param) @property > pure @safe > { > Field = param; > m_matrixCalculated = false; > } > > alias pos = SetProperty!(float[], m_pos); > alias pos = SetProperty!(Vector4, m_pos); > alias ratio = SetProperty!(float, m_ratio); > alias near = SetProperty!(float, m_near); > alias far = SetProperty!(float, m_far); > } > > I get this kind of compilation error: > Error: template instance SetProperty!(float[], m_pos) cannot use > local 'm_pos' as parameter to non-global template > SetProperty(Tin, alias Field)(ref Tin param) > > I don't understand why that error occurs. > > And I cannot find any elegant solutions (even with mixin's) to > declare a template and then instantiate it in a single line to > define the methods I want. > > Does any of you have an idea? > > Thanks class Camera { private: int m_pos; float m_fov, m_ratio, m_near, m_far; bool m_matrixCalculated; public: mixin template opAssign(alias Field) { void opAssign(Tin)(auto ref Tin param) @property pure @safe { Field = param; m_matrixCalculated = false; } } mixin opAssign!(m_pos) pos; mixin opAssign!(m_fov) fov; mixin opAssign!(m_ratio) ratio; mixin opAssign!(m_near) near; mixin opAssign!(m_far) far; } void main() { Camera cam = new Camera(); cam.fov = 1.0; stdin.readln; }