(Rephrased the question)
I’m creating a wrapper class for boost normal distribution, and want to make it as efficient as possible.
If I use:
double x = 0.0;
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);
for (int i=0; i<20; i++) {
double x = var_nor();
}
The loop works fine. My concern is that I don’t want to be declaring anything unnecessarily as the method gets called many times. I tried splitting up the code and put this line in the constructor:
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);
and have a sample method that does this:
double x = var_nor();
return x;
But in this case, I get an error saying var_nor() (ie. with no arguments) is not found.
Can anyone tell me what’s going on with these boost declarations ie. what does the
boost:variate_generate etc.
line actually do in with var_nor?
With my limited C++ knowledge, it looks as if var_nor is being defined with two different signatures.
Thanks guys
Pete
In your code,
var_noris a variable, not a function, so it doesn’t have a signature. It represents avariate_generatorobject that can behave like a function because it supportsoperator().In your code, you declare and initialize
var_norat the same time. Therngandndarguments are passed to the constructor of thevariate_generatorobject.When you moved the declaration into your class’s constructor, you were declaring
var_noras a local variable in the constructor, so it’s no wonder it wasn’t available elsewhere. For something to be available throughout an entire class, it needs to be a member variable. Declare it private in the class:Then initialize it in the constructor:
The
_rngmember needs to be declared first so that it will be initialized first. Thendparameter can be omitted and replaced with a temporarynormal_distributionobject passed directly to thevar_norconstructor as shown above.With those changes, you should be able to use the same
normal_distributionobject over multiple calls to yoursamplefunction, or whatever other uses you have for yourNormalDistributionclass.In the code you’ve since deleted from your question, you were confusing variable declarations with function declarations. You declared
ndas a function receiving two parameters and returning anormal_distribution. Likewise withvar_nor. It was a function when you really wanted an object. You were confused because it happens to be an object that acts like a function, but it’s still just an object.