mardi 3 juillet 2018

Template to match custom functors or stod, stoi, etc

I'm trying to store key-value parameters as string in a class named ModelConfig. Then I would like to automatically convert these values into specific types, either with custom conversion function or with standard functions stod, stof, stoi, and the like.

My class successfully parses parameters if I provide a custom conversion function, but I can't figure how to also accept standard functions. This is my approach:

class ModelConfig
{
public:
    ModelConfig(void) = default;

    void addParam(std::string pname, std::string pvalue) {
        m_params[pname] = pvalue;
    }

    template <class F, typename... Args, class T = typename std::result_of<F&&(const std::string&, Args...)>::type>
    T getParam(std::string pname, F&& pconv_functor) const
    {
        return pconv_functor(m_params.at(pname));
    }

private:
    std::map<std::string, std::string> m_params;
};

The class above, can be tested with:

#include <iostream>
#include <map>
#include <functional>
#include "ModelConfig.hpp"

int main(void)
{
    ModelConfig mc;
    mc.addParam("p1_float",  "123.4");
    mc.addParam("p2_double", "56.7");
    mc.addParam("p3_bool",   "true");
    mc.addParam("p4_int",    "-321");

    auto functord = [](const std::string& s) {
        return std::stod(s);
    };

    std::cout << mc.getParam("p2_double", functord) << "\n";  // OK.
    std::cout << mc.getParam("p2_double", std::stod) << "\n"; // Error.

    return 0;
}

How can I modify getParam to accept functions where their first argument is a string but which can have others with default values?

Aucun commentaire:

Enregistrer un commentaire