I want to be able to do this:

Pass a parameter to my main program like "parallel = yes"

and then many functions down in the hierarchy (ie main calls "Function1" which calls "Function2" which calls "Function3", etc) I need to see the value of "parallel". I'd hate to have to pass it to every function along the way even though they will never look at it. Is there a better way to do this?

Thanks,

Dave

Recommended Answers

All 3 Replies

How about storing those options in a singleton:

#include <iostream>
#include <string>

namespace EdRules {
  using namespace std;

  class GlobalOptions {
  public:
    string parallel;

    static GlobalOptions& Get()
    {
      static GlobalOptions options;
      return options;
    }
  private:
    GlobalOptions() {}
    GlobalOptions(const GlobalOptions&) {}
    GlobalOptions operator=(const GlobalOptions&) {}
  };
}

void bar()
{
  using namespace std;
  using namespace EdRules;

  cout << GlobalOptions::Get().parallel << '\n';
}

void foo()
{
  bar();
}

int main(int argc, char **argv)
{
  using namespace EdRules;

  GlobalOptions::Get().parallel = argv[1];
  foo();
}

awesome - sounds about perfect. Can I put the GlobalOptions class in a separate file (GlobalOptions.h) and then include it normally (ie. #include "GlobalOptions.h) and use it the same way?

Also, does it have to be in a namespace?

Thanks,
Dave

Can I put the GlobalOptions class in a separate file (GlobalOptions.h) and then include it normally (ie. #include "GlobalOptions.h) and use it the same way?

#include is just a fun way of doing cut and paste. Separating code into header files shouldn't change how you use a class or make it less useful. :)

Also, does it have to be in a namespace?

It doesn't, but using a namespace is a good idea in any case. Edward uses the namespace in this example to shrink the scope of using namespace std; so that it isn't in the global scope. But namespaces are a great tool for organization too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.