samedi 4 septembre 2021

How to pass const struct pointer to a setter method in C++

I am trying to pass a const struct pointer to a setter setContainer of an auto-generated C++ API code so I can't change the class:

#include <iostream>
#include <memory>

class Class // Class definition
{
public:
    struct Container    // Container definition
    {
        double value = 0.0;
    };

    Class() { } // constructor
    ~Class() { } // destructor

    void setContainer(const Container * pContainer)
    {   
        mContainer = *pContainer; // setter
    }

    const Class::Container & getContainer() const
    {
        return mContainer; // getter
    }

private:
    Container mContainer;
};

As you can see I don't know how to pass the struct object to setContainer method in the correct manner. Smart pointers would be even better as I am using C++14.

int main()
{    
    Class objClass; 

    const auto container1 = objClass.getContainer();

    // Output: container1.value: 0.0
    std::cout << "container1.value: " << container1.value << std::endl; 
    
    // Need to set this at runtime
    Class::Container container2;
    container2.value = 5.0; 

    // Output: container2.value: 5.0
    std::cout << "container2.value: " << container2.value << std::endl; 
    
    // ERROR: no matching function for call to ‘Class::setContainer(Class::Container&)’
    objClass.setContainer(container2); 
    
    const auto container3 = objClass.getContainer();

    // Desired Output: container3.value: 5.0 (set by setContainer)
    std::cout << "container3.value: " << container3.value << std::endl; 

    return 0;
}

I'd really appreciate some help getting this right.

Aucun commentaire:

Enregistrer un commentaire