Define methods using templates
    Steven Schveighoffer via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Dec 30 05:48:13 PST 2014
    
    
  
On 12/30/14 8:17 AM, Claude wrote:
> 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.
I think it has to do with the fact that when you are defining the 
aliases, m_pos for example, is an *instance* member so requires an 
instance to get an alias.
What you are probably better off doing is:
void SetProperty(Tin, string Field)(ref Tin param) @property pure @safe
{
    mixin(Field ~ " = param;");
    m_matrixCalculated = false;
}
alias pos = SetProperty!(float[], "m_pos");
I would also put some strict template constraints on the Field string 
too, because one abuse SetProperty pretty easily there.
-Steve
    
    
More information about the Digitalmars-d-learn
mailing list