(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.


Description: Avoiding a profusion of get/set.

Keywords: ecl parameters

Tutorial Level: INTERMEDIATE


  • Parameter types substitute the basic types for a more convenient templatised structure when used within a class. Ideally the only way any member variable should be modified is via member functions of the class itself. When you start allowing member variables to be extracted and modified outside a class, you inevitably lose control of the class (and in practice this happens by lazy/tired programmers more often than not) and bugs start creeping in. The usual way to implement this is with get and set methods providing access. However, this can get somewhat verbose for simple classes:

   1 class A {
   2 public:
   3     A() {};
   5     int getCounter() const { return m_counter; }
   6     void setCounter (const int& counter) { m_counter = counter; }
   8 private:
   9     int m_counter;
  10 };

This can be simplified with the use of templates and the () operator resulting in the Parameter class defined here.

Compiling & Linking

Include the following at the top of any translation unit that requires compilation of class that uses parameters.

   1 #include <ecl/utilities.hpp>
   3 using ecl::Parameter;

Since it is a template class, no linking is required if you are only using this class.



The parameter implementation of a class A (compare with the set/get implementation described earlier) looks like:

   1 class A {
   2 public:
   3     A() {};
   5     Parameter<int> counter;
   6 };

Here access to the variable is done very similarly (but without the verbosity of set/get).

   1 int main() {
   2     A a;
   3     a.counter(1); // <-- Sets the variable
   4     cout << a.counter(); << endl; // <-- Gets the variable
   5 }

Note that even though Parameter<int> is defined publicly, the contents are

  • still privately allocated, but here they are tucked away in Parameter's internal implementation.


There are also convenience methods if the above usage is undesirable.

   1 a.counter = 1;
   2 int a_copy = a.counter;

The difference between these and public variables is that these can never be set outside of the class. The reason - regualar public variables can be hooked by a pointer/reference and then passed off to another function where the variable can be modified...well outside of the control of the original class. In this case here, the only hooks that can be made to the variable are const pointers or const references. Thus, even though the notation is the same, these parameter variables are protected by their constness.

Wiki: ecl_utilities/Tutorials/Parameters (last edited 2012-02-01 14:09:54 by DanielStonier)