[Documentation] [TitleIndex] [WordIndex

(!) 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.

Parameters

Description: Avoiding a profusion of get/set.

Keywords: ecl parameters

Tutorial Level: INTERMEDIATE

Introduction

   1 class A {
   2 public:
   3     A() {};
   4 
   5     int getCounter() const { return m_counter; }
   6     void setCounter (const int& counter) { m_counter = counter; }
   7 
   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>
   2 
   3 using ecl::Parameter;

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

Usage

Parameters

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

   1 class A {
   2 public:
   3     A() {};
   4 
   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

Convenience

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.


2020-01-25 12:37