3

I think that any explanation without the code would be just more obscure. So here is the code where I tried to keep everything as simple as possible.

#include <vector>
#include <iostream>

class WithParametersBase
{
public:
    WithParametersBase();

    double getX() const {return 0.0;}
    double getY() const {return 1.0;}

    //let's say I want to access these members using an unified interface:

    double getParameter(int index) const;

    // For example index == 0 means getX and index == 1 means getY.
    // I could implement it for example like this:

protected:

    void addGetter(double (WithParametersBase::* getter)()const)
    {
        getters_.push_back(getter);
    }

    std::vector<double (WithParametersBase::*)()const> getters_;
};

WithParametersBase::WithParametersBase()
{
    addGetter(&WithParametersBase::getX);
    addGetter(&WithParametersBase::getY);
}

double WithParametersBase::getParameter(int index) const
{
    return (this->*(getters_[index]))();
}

Indeed it works. With a test program:

int main(int argc, char *argv[])
{
   WithParametersBase base;

   std::cout << base.getParameter(0)
             << base.getParameter(1) << std::endl;

   return 0;
}

The printout is correct:

01

But in case I wnat to extend this class:

class WithParametersDerived : public WithParametersBase
{
public:
    WithParametersDerived();
    double getZ() const  {return 2.0;} // A new getter
};

WithParametersDerived::WithParametersDerived()
{
    // I want to integrate the new getter into the previous interface
    addGetter(&WithParametersDerived::getZ); 
}

so that if I call:

WithParametersDerived derived;
std::cout << derived.getParameter(2) << std::endl;

I want to get get a

2

I cannot compile the program. I get an error:

error: no matching function for call to
'WithParametersDerived::addGetter
(double (WithParametersDerived::*)()const)'

Which is reasonable, but I do not know how else to implement it.

I want the creator of the derived class to be able to just add the new getter. I know, that it somehow doesn't feel right doing all this at runtime, but I do not see a template solution or a preprocessor solution. If you have some suggestions, please let me know. Anything!

8
  • Are you trying to do this for fun (because you want to figure out how to do it) or for profit (you actually need to accomplish something)?
    – reuben
    Jul 4, 2012 at 4:33
  • The double getParameter(int index) const; function is used by other classes in the program. These are aware only of the base class. But if I extend the base class, I want the other classes in the system to be aware of this Jul 4, 2012 at 4:36
  • my question was more along the lines of -- what broader purpose is getParameter serving? It seems like the sort of mechanism that's prone to confusion or issues over time...
    – reuben
    Jul 4, 2012 at 4:39
  • That is, this is an actual problem I need to figure out to continue my work. Jul 4, 2012 at 4:39
  • 1
    The actual code problem is that you're using class member function pointers, and the type of a member function in the base class is not equal to the type of a member function in a derived class. I'm not sure it's the best overall option, but you could consider using non-member function pointers instead, and capture pointers to static class functions.
    – reuben
    Jul 4, 2012 at 4:42

1 Answer 1

6

I'll sidestep the why you need such a scheme, and focus on the how.

Instead of member function pointers, you can use a std::function<double ()>, which is a generic wrapper around any callable entity having the signature double foo(). To create a std::function<double ()> out of a member function and an object instance, you use std::bind as follows:

std::function<double ()> callback =
    std::bind(&Class::memberFunction, objectInstancePointer);

If you're not using C++11, std::function and std::bind are also available in Boost as boost::function and boost::bind. The Boost documentation for these are mostly (if not entirely) applicable to their C++11 counterparts.

Instead of a std::vector, you can use a std::map to index getters by name. This may be more practical than maintaining a central list of parameter ID numbers.

If your parameters can be of different type than double, then you may want to consider using boost::any or boost::variant as the return type.

Here's a complete working example using std::function, std::bind, and std::map:

#include <cassert>
#include <map>
#include <iostream>
#include <functional>

class WithParametersBase
{
public:
    WithParametersBase()
    {
        addGetter("X", std::bind(&WithParametersBase::getX, this));
        addGetter("Y", std::bind(&WithParametersBase::getY, this));
    }

    virtual double getX() const {return 0.0;}
    virtual double getY() const {return 1.0;}

    // Access parameter by name
    double getParameter(const std::string& name) const
    {
        auto getterIter = getters_.find(name);
        assert(getterIter != getters_.end());
        return getterIter->second();
    }

protected:
    typedef std::function<double ()> ParameterGetter;
    typedef std::map<std::string, ParameterGetter> GetterMap;

    void addGetter(const std::string& name, const ParameterGetter& getter)
    {
        getters_[name] = getter;
    }

    GetterMap getters_;
};

class WithParametersDerived : public WithParametersBase
{
public:
    WithParametersDerived()
    {
        addGetter("Z", std::bind(&WithParametersDerived::getZ, this));

        // Override base class getX
        addGetter("X", std::bind(&WithParametersDerived::getX, this));
    }

    double getX() const {return 3.0;} 
    double getZ() const {return 2.0;} // A new getter
};

int main(int argc, char *argv[])
{
    WithParametersBase base;
    WithParametersDerived derived;
    WithParametersBase& polymorphic = derived;

    std::cout << base.getParameter("X")
              << base.getParameter("Y")
              << polymorphic.getParameter("X")
              << polymorphic.getParameter("Y")
              << polymorphic.getParameter("Z") << std::endl;

    return 0;
}

The downside of this approach is that each instance of WithParametersBase (or a descendant) will contain a GetterMap. If you have a large amount of such objects, the memory overhead of all those GetterMaps may be undesirable.


Here's a more efficient solution that does away with std::function and std::bind. Regular function pointers and static member functions are used for getter callbacks. The object instance for which a parameter is requested is passed as an argument to these static member functions. In derived types, the instance reference is first downcast to the derived type before invoking the member function that does the actual getting.

There is now only one GetterMap per class instead of per object. Note the use of the "construct on first use" idiom in the getters() method to avoid static initialization order fiasco.

The downside with this solution is that there is more boilerplate code to write for each class derived from WithParametersBase. It might be possible to reduce the amount of boilerplate code using templates (it would definitely be possible with macros).

#include <cassert>
#include <map>
#include <iostream>

class WithParametersBase
{
public:
    virtual double getX() const {return 0.0;}
    virtual double getY() const {return 1.0;}

    // Access parameter by name
    double getParameter(const std::string& name) const
    {
        auto getterIter = getters().find(name);
        assert(getterIter != getters().end());
        return getterIter->second(*this);
    }

protected:
    typedef double (*ParameterGetter)(const WithParametersBase& instance);
    typedef std::map<std::string, ParameterGetter> GetterMap;

    static double xGetter(const WithParametersBase& instance)
    {
        return instance.getX();
    }

    static double yGetter(const WithParametersBase& instance)
    {
        return instance.getY();
    }

    static GetterMap makeGetterMap()
    {
        GetterMap map;
        map["X"] = &WithParametersBase::xGetter;
        map["Y"] = &WithParametersBase::yGetter;
        return map;
    }

    virtual const GetterMap& getters() const
    {
        // Not thread-safe. Use std::call_once to make thread-safe.
        static GetterMap map = makeGetterMap();
        return map;
    };
};

class WithParametersDerived : public WithParametersBase
{
public:
    double getX() const {return 3.0;} 
    double getZ() const {return 2.0;} // A new getter

protected:
    static double zGetter(const WithParametersBase& instance)
    {
        // It's reasonably safe to assume that 'instance' is of type
        // WithParametersDerived, since WithParametersDerived was the one
        // that associated "Z" with this callback function.
        const WithParametersDerived& derived =
            dynamic_cast<const WithParametersDerived&>(instance);
        return derived.getZ();
    }

    static GetterMap makeGetterMap()
    {
        // We "inherit" the getter map from the base class before extending it.
        GetterMap map = WithParametersBase::makeGetterMap();
        map["Z"] = &WithParametersDerived::zGetter;
        return map;
    }

    virtual const GetterMap& getters() const
    {
        // Not thread-safe. Use std::call_once to make thread-safe.
        static GetterMap map = makeGetterMap();
        return map;
    };
};

int main(int argc, char *argv[])
{
    WithParametersBase base;
    WithParametersDerived derived;
    WithParametersBase& polymorphic = derived;

    std::cout << base.getParameter("X")
              << base.getParameter("Y")
              << polymorphic.getParameter("X")
              << polymorphic.getParameter("Y")
              << polymorphic.getParameter("Z") << std::endl;

    return 0;
}
5
  • I am not sure the name would be better than the index. At the end of the day, it's just a magical constant. The advantage of indexes is that you immediately know the range of available indexes, do you plan to keep a list of available names around ? Jul 4, 2012 at 6:17
  • @Emile Thank you very much for all! Also for suggestions with std::map and boost::variant! Jul 4, 2012 at 6:23
  • 1
    @MartinDrozdik : See edit for a more efficient solution (but with more boilerplate code). Jul 4, 2012 at 6:53
  • @MatthieuM.: With names, there are less maintenance headaches compared to allocating numbers. For example: enum {position=0, speed=1, voltage=2, current=3};. Now consider an extension would like to add the acceleration parameter. But it has to know that the next available number is 4, and that it's not already used by some other extension. Furthermore, acceleration belongs with the other spacial measurements, but now it's stuck in after the electrical measurements. Yuck! :) Jul 4, 2012 at 7:48
  • @EmileCormier: I think we disagree on the use of the tool. If you need the "acceleration", then use getAcceleration. If you need to iterate, then use: for (size_t i = 0, max = base.getNbParameters(); ...). Note that there is no reason to change your enum to insert acceleration after speed. If everyone uses the enum, it just works :) Jul 4, 2012 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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