You are currently browsing the archives for the C++ tag.

Bitesize Modern C++ : constexpr

May 21st, 2015

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

A constant expression is an expression that can be evaluated at compile-time. The const qualifier gives a weak guarantee of a constant expression – a const-qualified type may not be changed after initialisation but that does not guarantee it will be initialised at compile-time. For example:

image

C++11 introduces a strong form of constant expression, constexpr, which also expands the capabilities of compile-time evaluation.

constexpr objects

A constexpr variable is essentially the same as qualifying the type as const with the additional requirement that its initialiser(s) must be known at compile-time. Any object type that could be made const can be made a constexpr object.  As expected, the object must be initialised on definition.  Note that literals are, by definition, constant expressions.

image

Since constexpr types have their value known at compile-time they can be placed in read-only memory; and, for built-in types (and provided you don’t take their address) the compiler doesn’t even have to store the object. We’ll look at user-defined (class)types in a moment.

constexpr functions

So far, so what?

The real power of constant expressions comes from the fact that not only objects but functions may be qualified as constexpr.

A constexpr function is one that may be evaluated at compile-time; and hence used in the definition of other constant expressions:

image

Of course, there are some limitations with constexpr functions:

  • They must have exactly one return statement
  • They cannot have local variables
  • They cannot have conditional expressions
  • They cannot throw exceptions
  • They cannot include a goto statement
  • All parameters must be (capable of being) constexpr objects

Put simply, in order to be a constexpr function everything the function needs to be computed must be known at compile-time. Making a function a constant expression implies it is inline.

(Note: C++14 relaxes some of these requirements with respect to local variables and conditionals).

Marking a function as a constexpr doesn’t limit it to only be usable at compile-time. They may still be used at run time:

image

ROM-able types

The use of constexpr for functions extends to member functions, too. Marking a member function as a constexpr implicitly makes it a const function, meaning it cannot change any of the attributes of the class.

This is also true of constructors. Making a class’s constructor a constexpr allows objects of that type to themselves be constexpr objects.

image

Since everything required to construct the Rommable object is known at compile-time it can be constructed in read-only memory.

In order to be truly ROM-able there are some additional requirements we must satisfy (over and above the requirements for a constexpr function):

  • The class cannot have any virtual functions (virtual functions cannot be constant expressions)
  • The class cannot have a virtual base class
  • All base classes and all const members must be initialised by the constructor

 

More information

Can’t wait? Download the full set of articles as a PDF, here.

To learn more about Feabhas’ Modern C++ training courses, click here.

Software Duct Tape – Binding the C++ Universe Together

December 4th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

One of the cornerstones of object-oriented design is the concept of objects interacting by sending messages to form mechanisms – units of higher-order (or ‘emergent’) behaviour.

In order to send a message (in this case, invoke a member function) an object must have a ‘link’ to the target object. That link is formed by building in an association between the two classes as part of the type’s definition.

In this article we look at building associations between classes and forming run-time links so objects can communicate.

The basic principle

An association represents the ability of one object to send a message (invoke a function) of another. In order to do that the sending object must know the identity of the receiver.

The identity of an object is its address; therefore we must hold the address of the receiver. An association between two classes is therefore implemented as a pointer to that type.

We also need a ‘binding’ function to encapsulate the linking of the two objects.

Connected objects form a system

image

In a client-server relationship the client invokes the services of the server. The client sends messages to the server. That is, the client invokes the member functions of the server. This relationship is uni-directional. The server never calls the client’s member functions.

In a peer-to-peer relationship either object may invoke the operations on the other. That is, the relationship is bi-directional.

Note: Just because a member function returns a value does not make the relationship bi-directional. The association type is determined by who makes the member function calls, not the direction of data travel.

Client-Server 1:1 association

The simplest, and probably most common, form of association is the unidirectional client-server.

image

In this example the Positioner class is the client, with two (independent) server classes – Actuator and Sensor. Here the identities of the server objects are stored as pointers; the constructor is used as the binding function.

We form the link by binding the actual objects together at run-time. In this example we bind the Actuator object and the Sensor object by passing in the addresses of these objects to the Positioner constructor.

image

The Positioner can now invoke member functions on its associated objects by dereferencing its pointers.

Improving the interface

Since a reference is an alias for an (existing) object, taking the address of a reference is the same as taking the address of the original object.

image

Or, put another way: since a reference acts as an automatically-dereferenced (const) pointer, taking the address of a reference is semantically equivalent to:

&(*(&pos));

image

Passing by reference hides from the client the fact that the CameraStabiliser stores pointers internally. This is yet another form of encapsulation.

A quick aside: Why not use references for associations?

In this simple case you could – and many programmers advocate this – use a reference to the server object instead of a pointer. I prefer to use a pointer for a number of reasons:

  • A pointer specifies that I am holding the address (identity) of an object; references are a mechanism for efficient parameter passing in functions. Let’s use the language idioms correctly and consistently
  • Pointers can be used consistently for all association types; references can’t. See below for more on this.
  • Since references can’t be re-seated using a reference ‘fixes’ the association. There’s no way to associate objects differently later in the program. This precludes the ability to do substitution of specialised types at run-time. This dramatically limits the flexibility of your design.  You’re probably better off using a template instead.

While we’re talking about pointers: don’t be tempted to use smart pointers for associations. The problem with a smart pointer is that it’s designed for use with dynamically-allocated objects. As a client you can’t (and shouldn’t) know the storage specification of your server object. If the server object is stack-based when your association smart pointer goes out of scope it will try and call delete on the address of the object (for those who haven’t experienced this, trust me – it never ends well).

Associations are one of the very few valid uses of ‘raw’ pointers in a C++ program.

1:N unidirectional associations

When the association is one-to-many then a simple pointer does not suffice. We could use individual (named) pointers but this would be a clumsy solution (at best). In this case we use a std::array to hold the pointers (since the maximum number of Position objects is fixed, at 16).

image

The moveTo() function acts as a ‘bind’ function. It adds the address of the associated object to the track array.

image

Notice that in this case we can’t use references to hold the identity of the object because you can’t have an array of references.

1:* Unidirectional associations

It’s a relatively trivial extension to implement a one-to-many association: simply replace the fixed-size array with a dynamic container (for example a std::list)

image

Bi-directional 1:1 associations

If our association is bi-directional, then both classes need pointers. The problems come when you have to bind the objects together: which object gets built first?

image

If both classes need a pointer to the other in their constructors to work there is a cyclic dependency.

One solution is to provide a ‘binder’ function on each class that forms the association. In this example, the UI class has an additional member function, addStabiliser() that allows a CameraStabiliser object to be bound to it. The CameraStabiliser class has a complementary function.

image

At construction time, the CameraStabiliser and UI objects are constructed. Then the objects are bound together by calling the ‘bind’ functions. Notice, the programmer must ensure that the objects are bound together before they are used, otherwise you may end up dereferencing null pointers! Having to check for null pointers may seem a major drawback of this technique but it should be remembered that, sometimes, your design may actually require an unfulfilled association.  If that isn’t the case, using an assert in your code during development will highlight that you have failed to construct your system correctly.

A consequence of this approach is that the public interface of a class becomes ‘polluted’ with bind functions, which have nothing to do with the class’s functionality. This breaks the Single Responsibility Principle, which says an object should only have one reason to change. In this case, our classes have two reasons to change: their behaviour, which is part of their design; and their set of associations, which is a function of how they will be used in this particular project. These two aspects are orthogonal.  For example, the same class could be used in a very different way in another project, meaning it would most likely have a very different set of associations; even though its behaviour hasn’t changed.

An alternative approach is to create a free function that binds the two objects together.

image

Note, now both objects only have default constructors. The bind function forms the association between the two objects.

This approach has the benefit that it does not add any (non-behavioural) functions to the public interface of either class.

However, there is a problem with this code.

image

The bind function is not a member of either the UI or CameraStabiliser classes, so therefore cannot access their private data members (in this case, the association pointers)

Making the pointers public would allow this code to work but this exposes the pointers to clients and breaks encapsulation.

The solution is to make the bind function a friend function. A friend function is granted access to the private members of the class.

image

Notice the bind function must be made a friend of both the UI and CameraStabiliser classes.

The above is the general case for forming associations: a pointer plus a friend bind function. This will work for all associations – even the simplest case (1:1 unidirectional). For consistency of code this is the method I generally promote.

image

Reducing compile-time dependencies

Including one header file within another builds a dependency (coupling) between the two interfaces. Wherever possible we want to reduce the coupling between modules in our design.

image

In this case, including the class definition of class Sensor is unnecessary. You only need to include the class definition if:

  • You are going to allocate memory for an object
  • Inherit from an class
  • Call one of the class’s member functions.

Class Positioner does not instantiate a Sensor object; it merely has a pointer to a Sensor object. Since the compiler knows how much memory to allocate for a pointer we do not need to include the class definition of Sensor.

However, we must still declare that class Sensor is a valid type to satisfy the compiler. In this case we do so with a forward reference – actually just a pure declaration that class Sensor exists (somewhere).

image

Note: if we wish to call any of Sensor’s member functions we must include the class definition.

image

Summary

Adopting consistent idioms is the core of building maintainable code; making every construct a special case just makes code difficult to read, understand, extend and adapt.

In an object oriented design classes don’t just exist in isolation: they are inter-connected and their interactions are what provide the system’s behaviour. Understanding the need for, and implementation of, associations is a basic, fundamental skill for any C++ programmer.

 

If you’d like to know more about C++ programming – particularly for embedded and real-time applications – visit the Feabhas website. You may find the following of interest:

C++-501 – C++ for Embedded Developers

C++-502 – C++ for Real-Time Developers

AC++-501 – Advanced C++

AC++11-401 – Transitioning to C++11.

DP-403 – Design patterns for C++

Traits classes

September 18th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

In this final article we’ll have a look at the issue of communicating template type information between different template instantiations, and have a look at the Traits mechanism as a method of solving these issues.

Read more »

Template specialisation

September 4th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

Welcome back to the wonderful world of templates.

So far, we have looked at what are known as base templates. In this article we’re going to look at one of the more confusing aspects of templates – specialisation. The choice of the word specialisation is unfortunate, as many confuse it with inheritance and sub-typing; in this case specialised means “more specific”.

Read more »

Templates of templates

August 21st, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

In this brief article we’ll have a look at the topic of building template classes whose parameters are themselves templates.

I’m assuming you’re reasonably familiar with template classes.  If not, here’s a quick introduction.

Read more »

Variadic templates

August 7th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

In this article we’re going to look at a new feature of templates in C++11 – the concept of the variadic template.

Variadic templates allow us to create functions and classes, not only with generic types, but also a variable number of generic types.

Read more »

Template member functions

July 24th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

Previously we’ve looked at template functions and we’ve looked at template classes. This time, let’s look at what happens when you combine them.

Read more »

Templates and polymorphism

July 10th, 2014

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

Latest posts by Glennan Carnie (see all)

Introduction

Template functions and classes tend to cause consternation amongst programmers. The conversation tends to go something like this:

  • I understand the syntax of templates (although it’s ugly)
  • I get the idea of replacing function-like macros with template functions
  • I can see the application of template classes for containers
  • Most containers and generic functions are library code
  • I don’t write libraries
  • What’s the point of me using templates?

In this article we’re going to look at an application of templates beyond writing library code – replacing run-time polymorphism (interfaces) with compile-time polymorphism. This idea is known as a Policy. The idea is reminiscent of the Strategy Pattern, but uses templates rather than interfaces.

Read more »

Native C/C++ Application development for the mbed using CMSIS-DAP

April 12th, 2013

If you have been following the Feabhas blog for some time, you may remember that in April of last year I posted about my experiences of using the MQTT protocol. The demonstration code was ran the ARM Cortex-M3 based mbed platform.mbed-microcontroller-angled

For those that are not familiar with the mbed, it is an “Arduino-like” development platform for small microcontroller embedded systems. The variant I’m using is built using an NXP LPC1768 Cortex-M3 device, which offers a plethora of connection options, ranging from simple GPIO, through I2C and SPI, right up to CAN, USB and Ethernet. With a similar conceptual model to Arduino’s, the drivers for all these drivers are supplied in a well-tested (C++) library. The mbed is connect to a PC via a USB cable (which also powers it), so allows the mbed to act as a great rapid prototyping platform. [I have never been a big fan of the 8-bit Arduino (personal choice no need to flame me  ) and have never used the newer ARM Cortex-M based Arduino’s, such as the Due.]

However, in its early guise, there were two limitations when targeting an mbed (say compared to the Arduino).

First was the development environment; initially all software development was done through a web-based IDE. This is great for cross-platform support; especially for me being an Apple fanboy. Personally I never had a problem using the online IDE, especially as I am used to using offline environments such as Keil’s uVision, IAR’s Embedded Workbench and Eclipse. Over the years the mbed IDE has evolved and makes life very easy for importing other mbed developers libraries, creating your own libraries and even have an integrated distributed version control feature. But the need Internet connection inhibit the ability to develop code on a long flight or train journey for example.

Second, the output from the build process is a “.bin” (binary) file, which you save on to the mbed (the PC sees the mbed as a USB storage device). You then press the reset button on the mbed to execute your program. I guessing you’re well ahead of me here, but of course that means there is no on-target debug capabilities (breakpoints, single-step, variable and memory viewing, etc.). Now of course one could argue, as we have a well-defined set of driver libraries and if we followed aTest-Driven-Development (TDD) process that we don’t need target debugging (there is support for printf style debugging via the USB support serial mode); but that is a discussion/debate for another session! I would hazard a guess most embedded developers would prefer at least the option of target based source code debugging? Read more »

Setting up googlemock with Visual C++ 2010 Express Edition

March 15th, 2012

Following on from my last post about setting up googletest to use with Visual Studio 2010 express edition, this post builds on that by showing how to build, setup and test the googlemock libraries.

If you have read the previous post, then the basic steps are very similar.

First, download the googlemock zip file and unzip it to known location. As before, I suggest something easy, either C:\gmock-1.6.0, or as in my case C:\src\gmock-1.6.0. One useful fact is that all the gtest code is included as part of the gmock distribution. It can be found at \gmock-1.6.0\gtest.

Building the gtest libraries

It is the same process as build the gtest libraries. One importany note is that

The gmock libraries contain all the gtest code as well.

Navigate to the directory \gmock-1.6.0\msvc\2010 and open the Visual C++ project gmock (gmock.sln). You will end up with three projects.

image

Go ahead and build these (F7) and ignore any warnings. Once successfully built, look in the directory \gmock-1.6.0\msvc\2010\gtest\Debug and you will find two library files

  • gmock.lib
  • gmock_main.lib

Test the GMock Library

As part of the standard build two executable are created that allow a quick self-test of googlemock (gtest does have the same but I neglected to mention those in my previous post).

I recommend opening a command window and navigating to directory  \gmock-1.6.0\msvc\2010\Debug. There you will fine the file gmock_test.exe; go ahead and execute that [NOTE: I had two (of the 830) tests fail, which I’m not sure why (yet) – to be investigated]

image
This indicates that (most of) gmock functions correctly.

Building a Base GMock Project

A gmock project is the same as  a gtest project but with different project properties. Create a newWin32 Console Application  project.  Add a test fixture file to the project:

testFixture.cpp
  1. #include “gtest/gtest.h”
  2. TEST(setup_test_case, testWillPass)
  3. {
  4.     EXPECT_EQ(42, 42);
  5. }
  6. TEST(setup_test_case, testWillFail)
  7. {
  8.     EXPECT_EQ(42, 0);
  9. }

and exclude file containing default main from build.

Modify the project properties (Alt+F7) as follows:

  • Set gmock and gtest header include directories
    • C/C++ -> General -> Additional Include Directories
      • \gmock-1.6.0\include
      • \gmock-1.6.0\gtest\include
  • Add gmock libraries (instead of gtest libs)
    • Linker -> General -> Addition Library Directories
      • \gmock-1.6.0\msvc\2010\Debug
    • Linker -> Input -> Additional Dependencies
      • gmock.lib
      • gmock_main.lib
  • Modify Runtime Library:
    • C/C++ -> Code Generation -> Runtime Library
      • Multi-threaded Debug (/MTd).

Note here that we don’t have to include the gtest libraries as these are embedded in the gmock libraries. Build and run and we will see the familiar gtest output:
image

To test the gmock setup we need to create two classes:

  • The class to become the Unit-Under-Test (UUT)
  • An interface class that the UUT calls upon, which doesn’t have any implementation (or the implementation is target/hardware specific).

Interface Class

IWidget.h
  1. class IWidget
  2. {
  3. public:
  4.     virtual void On() = 0;
  5.     virtual void Off() = 0;
  6. };

Unit Under Test

WidgetController.h
  1. class IWidget;
  2. class WidgetController
  3. {
  4. public:
  5.     WidgetController(IWidget& w);
  6.     ~WidgetController(void);
  7.     void exec();
  8. private:
  9.     IWidget& myWidget;
  10. };
WidgetController.cpp
  1. #include “WidgetController.h”
  2. #include “IWidget.h”
  3. WidgetController::WidgetController(IWidget& w):myWidget(w)
  4. {
  5.     myWidget.Off();
  6. }
  7. WidgetController::~WidgetController()
  8. {
  9.     myWidget.Off();
  10. }
  11. void WidgetController::exec()
  12. {
  13.     myWidget.On();
  14. }

Testing using the Mock framework

To test using the Mock we need to:

  1. Include the gmock header [line 3]
  2. Create a mock class derived from the Interface class [lines 7-12]
  3. Create a test where the UUT calls on the interface on the mock object [lines 16-23]
  4. Set the mock objects expectation [line 20]. The mock expectation is that the Off member function will be called twice, once during WidgetController construction and once during destruction.
Using the mock
  1. // testFixture.cpp
  2. #include “gtest/gtest.h”
  3. #include “gmock/gmock.h”
  4. #include “IWidget.h”
  5. class MockWidget : public IWidget
  6. {
  7. public:
  8.     MOCK_METHOD0(On, void());
  9.     MOCK_METHOD0(Off, void());
  10. };
  11. #include “WidgetController.h”
  12. TEST(TestWidgetController, testConstructor)
  13. {
  14.     MockWidget mw;
  15.     EXPECT_CALL(mw, Off()).Times(2);
  16.     WidgetController wc(mw);
  17. }

Build and run

image

You can see gmock in action by simply changing the expectation, e.g. [line 6]

Failing Test
  1. TEST(TestWidgetController, testConstructor)
  2. {
  3.     MockWidget mw;
  4. //    EXPECT_CALL(mw, Off()).Times(2);
  5.     EXPECT_CALL(mw, Off());
  6.     WidgetController wc(mw);
  7. }

will result in the following failed test output:

image

Where next?

Once you have a working project, the documentation on the Googlemock site is excellent. Start with Googlemock for Dummies.

%d bloggers like this: