mardi 1 octobre 2019

Why do I get the compiler error "does not name a type" when my code is outside of a function scope?

I was testing a game engine I am building by generating objects at random positions when I stumbled across this error that I do not understand.

"foo.h":

#include <random>
#include <chrono>
#include <functional>

namespace foo {

std::default_random_engine r_gen;
auto r_seed = std::chrono::system_clock::now().time_since_epoch().count();

r_gen.seed(r_seed);  // This is the line giving an error

std::uniform_real_distribution<float> r_dist(-1.0, 1.0);
auto r_float = std::bind(r_dist, r_gen);

}

"main.cpp":

#include <iostream>
#include "foo.h"

int main() {

    // Actually run the program

}

Attempting to compile this code gives me the error message:

error: 'r_gen' does not name a type
r_gen.seed(r_seed);
^~~~~

I am using Eclipse with MinGW. I'm not sure why it is interpreting r_gen as a type. And furthermore, wrapping the above code in a function (everything inside namespace foo) allows it to compile correctly.

I have a theory question and a pragmatic question:

  • (Theory) Why does my example code not compile?
  • (Pragmatic) How should I be arranging this code so that it only seeds the generator once?

Aucun commentaire:

Enregistrer un commentaire