c++c++11operator-overloadinglibconfig

c++ passing class instance as float variable in libconfig++ :: lookupValue()


I have this small class that revolves around a single double variable

class SensorTrainData
{
    public:
        SensorTrainData() : trainingRangeFactor(2.0f) {}
        SensorTrainData( const double & _factor ) { setFactor(_factor); }

        SensorTrainData & operator=(const double& other)
        {
             setFactor(other);
             return *this;
         }

         operator double() const
         {
             return getFactor();
         }

    private:

        void setFactor( const double & factor );
        const double & getFactor() const { return trainingRangeFactor; }

        double trainingRangeFactor; 
};

These user function double() and the operator "=" overload allow me to do respectively

SensorTrainData std(3.0f);
double d = std;

double k = 4.0f;
std = k;

I am using libconfig++ and I want to be able to pass the variable std directly in the libconfig::lookupValue("varName" , std) in order to pick value "varName", which was read in from a config (text) file.

Unfortunately, the compiler says I cannot pass a SensorTrainData & .

src/sensor.cpp:1048:45: error: no matching function for call to ‘libconfig::Setting::lookupValue(const char [12], enalu::SensorTrainData&) const’
src/sensor.cpp:1048:45: note: candidates are:
...
....
/usr/include/libconfig.h++:255:8: note: bool libconfig::Setting::lookupValue(const char*, double&) const
/usr/include/libconfig.h++:255:8: note:   no known conversion for argument 2 from ‘enalu::SensorTrainData’ to ‘double&’

of course I could do

double foo = 0.0f;
libconfig::lookupValue("varName" , foo); //load varName from file into foo
std = foo;

But I want to avoid the extra typing and code lines etc.

IS there an operator overload trick I could use to do that?

Thank you


Solution

  • Your problem is about const-ness: you're trying to convert std to a non-const reference while your operator double is const and relies on getFactor which returns a const reference.

    The following code works as intended:

    class SensorTrainData
    {
        public:
            SensorTrainData() : trainingRangeFactor(2.0f) {}
            SensorTrainData( const double & _factor ) { setFactor(_factor); }
    
            SensorTrainData & operator=(const double& other)
            {
                setFactor(other);
                return *this;
            }
    
            operator double&()
            {
                return getFactor();
            }
    
        private:
    
            void setFactor( const double & factor ) { trainingRangeFactor = factor; }
            double & getFactor() { return trainingRangeFactor; }
    
            double trainingRangeFactor; 
    };
    

    The obvious drawback is that you're now exposing trainingRangeFactor as a non-const reference.