title: How to use macros or C++ templates to allow reusable code in both host and device code?
body: <p>I'm writing a hobby raytracer in CUDA and C++ and I'm running into an issue that I haven't been able to get an answer on. I have written CPU and GPU code such that it can execute on machines with or without CUDA-capable devices. However, this has lead to some code duplication in the following sense:
  A small set of functions require random number generation, which is achieved with <code>stdlib</code> on host and <code>curand</code> on device. I would love to have <code>__host__ __device__</code> functions that take a <code>Sampler</code> struct that either calls <code>rand()</code> on host or <code>curand_uniform()</code> on device. I've tried some things but can't get the program to compile - the compiler complains about not calling <code>__device__</code> functions from <code>__host__</code> code and vice versa.</p>
  
  <p>Ideally I'd like my rendering functions to take a <code>Sampler *</code> which looks something like the code below.</p>
  
  <p>Thanks!</p>
  
  <pre><code>struct Sampler {
      __host__ virtual float getNextFloat() { return rand() / (RAND_MAX + 1.f); }
  };
  
  struct CudaSampler : Sampler { 
      curandState* p_curandState;
      __device__ float getNextFloat() { return curand_uniform(p_curandState); }
  };
  </code></pre>