简体   繁体   中英

C++ Variadic parameters

I am designing a convenient config object which will load config values from a file. In order to make sure there are sane defaults, the programmer can state for each kind of value what type it is, and a default value. That way, the config file can be checked and any incorrect can be immediately found. For example, consider the following config file httpd.conf:

port    8080
htdocs  ROOT
prelude true

and a config object in main:

int main() {
  Config conf("httpd.conf",
    "port", Config::INT, 80,
    "htdocs", Config::STRING, "default/",
    "preload", Config::BOOLEAN, false);

The above code would load the file and verify that port is in fact an integer, it would load htdocs , and it would find that "prelude" in the file does not match any registered value in the config, and emit an error:

line 3: undefined configuration item "prelude"

I could implement the above with an old C variadic parameters, but those are not typesafe. Is there any way to do it with the new C++ variadic parameters? The examples I have seen are all monotyped. Here I have triples of values.

I would like to design something that is easy to write in a single large call, but that is typesafe.

Without using variadic templates or functions and avoiding type elision you might do:

#include <sstream>
#include <stdexcept>

class Configuration
{
    public:
    Configuration(const std::string& resource)
    // Initialize the resources: Program options, environment variables, files
    {}

    /// Get a raw configuration value for a key.
    /// Reurns true if the key exists
    bool get_raw(const std::string key, std::string& result) const {
        // Find the key in supplied resources and set the result string
        // trimming leading and trailing spaces
        return false;
    }

    template <typename T>
    T get(const std::string key) const;

    template <typename T>
    T get(const std::string key, const T& default_value) const;
};

template <typename T>
T Configuration::get(const std::string key) const {
    std::string str;
    if( ! get_raw(key, str)) throw std::runtime_error("Invalid Key");
    else {
        T result;
        std::istringstream is(str);
        is.unsetf(std::ios_base::basefield);
        is >> result;
        if( ! is.eof() || is.fail()) throw std::runtime_error("Invalid Value");
        return result;
    }
}

template <typename T>
T Configuration::get(const std::string key, const T& default_value) const {
    std::string str;
    // There might be a dilemma - is a non existing key an error?
    if( ! get_raw(key, str)) return default_value;
    else if(str.empty()) return default_value;
    else {
        T result;
        std::istringstream is(str);
        is.unsetf(std::ios_base::basefield);
        is >> result;
        if( ! is.eof() || is.fail()) throw std::runtime_error("Invalid Value");
        return result;
    }
}


// Usage
struct HttpConfiguration : public Configuration
{
    unsigned port;
    std::string htdocs;
    bool preload;

    HttpConfiguration()
    :   Configuration("httpd.conf"),
        port(get<unsigned>("port", 80)),
        htdocs(get<std::string>("htdocs", "default/")),
        preload(get<bool>("prelude", false)) // typo here
    {}
};

Note: The class configuration can be anything managing configuration sources (have a look at Boost, POCO, ...).

Just to get you started if you want to use variadic templates:

template <class T>
struct Param {
  using Type = T;
  std::string name_;
  T default_value_;
};

template <class T>
auto MakeParam(std::string name, T default_value) -> Param<T> {
  return {name, default_value};
}

template <class T, class... Args>
auto ReadParams(Param<T> p, Args... args) -> void {
  ReadParams(p);
  ReadParams(args...);
}

template <class T>
auto ReadParams(Param<T> p) -> void {
  // here you can read from file
  cout << "param: '" << p.name_ << "' type: '"
       << typeid(typename Param<T>::Type).name() << "' defval: '"
       << p.default_value_ << "'" << endl;
}

int main() {
  ReadParams(MakeParam("param1", 0), MakeParam("param2", true),
             MakeParam("param3", "c-string"),
             MakeParam("param4", std::string{"c++str"}));

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM