1
\$\begingroup\$

Currently the class takes a json file and retrieves data from it, and i'd like to improve this class.

ConfigLoader.h

#ifndef LEVELEDITOR_CONFIGLOADER_H
#define LEVELEDITOR_CONFIGLOADER_H

#include <string>
#include <json/json.h>
#include <stdexcept>
#include <fstream>

namespace Editor
{
    class JsonInit
    {
    public:
        JsonInit()
        {
            std::ifstream inputFile("config.json");
            if (inputFile.bad())
            {
                throw std::runtime_error("could not load config file");
            }

            inputFile >> _root;
        }

        inline Json::Value& getRoot() { return _root; }

    private:
        Json::Value _root;
    };

    class ConfigLoader
    {
    public:
        inline static int loadInt(const std::string key) {return json.getRoot().get(key, -1).asInt(); }
        inline static std::string& loadString(const std::string key) {return json.getRoot().get(key, -1).asString();}

    private:

        static JsonInit json;
    };
}

#endif // LEVELEDITOR_CONFIGLOADER_H

ConfigLoader.cpp

#include "configloader.h"

Editor::JsonInit Editor::ConfigLoader::json;

Edit: forgot to say the "config.json" path is temporary, as i wish to make it possible to let the user choose

\$\endgroup\$
1
  • \$\begingroup\$ Is the configuration set or does it allow random values. If fixed then I would look at ThorsSerializer as it requires zero code to load the config file into a C++ object, \$\endgroup\$ – Martin York Sep 9 '20 at 20:54
2
\$\begingroup\$

It appears that the file ConfigLoader.cpp is unnecessary unless you are just providing an example of usage.

The keyword inline is obsolete, it is really only a suggestion these days. Modern C++ compilers will make the decision on whether the code should be inlined or not when using the -O3 switch.

If you are going to let the user define the config file name, then pass the name into the constructor and default it at a higher level.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.