Why does Simulink generate this code for a PID controller?
I'm not sur exactly where you went wrong because your haven't fully explained your approach but for the derivate component of the PID, you should convert the C++ lines to this :
$$ D_{out}[n] = N(err[n]D  -F[n-1]) \\  
F[n] = F[n-1] + T_s*D_{out}[n] \\\\$$
In the z-domain : $$
F(1-z^{-1}) = T_s*D_{out} \\
F = \frac{T_s*D_{out}}{1-z^{-1}}\\
D_{out} = N(err * D-Fz^{-1}) \\
D_{out} = N(err*D-\frac{T_sD_{out}}{1-z^{-1}}z^{-1}) \\ 
D_{out}(1+\frac{NT_sz^{-1}}{1-z^{-1}}) = N(err*D) \\ 
\frac{D_{out}}{err} = \frac{N*D}{1+\frac{NT_sz^{-1}}{1-z^{-1}}} \\
\frac{D_{out}}{err} = \frac{N*D}{1+\frac{NT_s}{z-1}}
$$
Edit :
You posted C++ code. Why is x_last only updated once? It needs to be updated every period. Try my solution below
double y0=0.0;
double Ts=0.005;
double PID_DifferentialPart(double x,double D,double N){
  static double x_last,y_last;
  static int first=1;
  double y;
  if(first){
    first=0;
    x_last = 0;
    y=y0;
  } else {
    y=D*N*(x-x_last)-(N*Ts-1.0)*y_last;
  }
  y_last=y;
  x_last=x;
  return y;
}