Search code examples
c++auto

C++ Using an auto-defined variable before knowing its type


I'm currently trying to use an auto-defined variable before knowing its type. Why? Because the type depends on the program input. If a user picks a certain distribution, the program will output values based on that distribution. Here's the code:

std::default_random_engine random_engine;
auto random;

if(from_dist)
{
    char* dist_name = strtok(distribution_name, "()");
    char* parameters = strtok(nullptr, "()");
    if(strcmp(dist_name, "gaussian") == 0)
    {
        double mean = atof(strtok(parameters, ","));
        double stddev = atof(strtok(nullptr, ","));
        std::normal_distribution<double> normal_distribution(mean, stddev);
        random = std::bind(normal_distribution, random_engine);
    }
        //TODO: Add more...
    else
    {
        std::cerr << "Invalid distribution. Known distributions:" << std::endl;
        std::cerr << "\tgaussian(mean,stddev) - gaussian (aka normal) distributions" << std::endl;
        exit(EXIT_FAILURE);
    }
}

However, C++ doesn't allow me to use an auto variable in this fashion. Is there any alternative that allows me to use the following snippet (later on the execution), without having to repeat it for each possible distribution?

while(true) {
        std::string message(OBSERVATION);
        for (int i = 0; i < FEATURE_COUNT; i++)
            message += " " + ((int) random());

        send(sock, message.c_str(), strlen(message.c_str()), 0);
        if (wait_time_ms)
            sleep(wait_time_ms);
}

Solution

  • The purpose of random (if I read your code correctly) is to become a callable object.

    You can solve your problem by making random a std::function object with the correct signature:

    std::function<double()> random;