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

Traits classes

September 18th, 2014

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

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

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

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

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

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.

Overcoming Name Clashes in Multiple C++ Interfaces

December 23rd, 2011

Interfaces

One of our key design goals is to reduce coupling between objects and classes. By keeping coupling to a minimum a design is more resilient to change imposed by new feature requests or missing requirements[1].

An Interface represents an abstract service. That is, it is the specification of a set of behaviours (operations) that represent a problem that needs to be solved.

An Interface is more than a set of cohesive operations. The Interface can be thought of as a contract between two objects – the client of the interface and the provider of the interface implementation.

The implementer of the Interface guarantees to fulfil the specifications of the Interface. That is, given that operation pre-conditions are met the implementer will fulfil any behavioural requirements, post-conditions, invariants and quality-of-services requirements.

From the client’s perspective it must conform to the operation specifications and fulfil any pre-conditions required by the Interface. Failure to comply on either side may cause a failure of the software.

Read more »

enum ; past, present and future

June 15th, 2011

The enumerated type (enum) is probably one of the simplest and most underused  features of the C and C++ which can make code safer and more readable without compromising performance.

In this posting we shall look at the basic enum from C, how C++ improved on C’s enum, and how C++0X will make them a first class type.

Often I see headers filled with lists of #defines where an enum would be a much better choice. Here is a classic example:

/* adc.h */
#define ADC_Channel_0                               (0x00) 
#define ADC_Channel_1                               (0x01) 
#define ADC_Channel_2                               (0x02) 
#define ADC_Channel_3                               (0x03) 
#define ADC_Channel_4                               (0x04) 
#define ADC_Channel_5                               (0x05) 
#define ADC_Channel_6                               (0x06) 
#define ADC_Channel_7                               (0x07) 
#define ADC_Channel_8                               (0x08) 
#define ADC_Channel_9                               (0x09) 
#define ADC_Channel_10                              (0x0A) 
#define ADC_Channel_11                              (0x0B) 
#define ADC_Channel_12                              (0x0C) 
#define ADC_Channel_13                              (0x0D) 
#define ADC_Channel_14                              (0x0E) 
#define ADC_Channel_15                              (0x0F) 

which probably would be better re-written as:

enum ADC_Channel_no {
	ADC_Channel_0,
	ADC_Channel_1,
	ADC_Channel_2,
	ADC_Channel_3,
	ADC_Channel_4,
	ADC_Channel_5,
	ADC_Channel_6,
	ADC_Channel_7,
	ADC_Channel_8,
	ADC_Channel_9,
	ADC_Channel_10,
	ADC_Channel_11,
	ADC_Channel_12,
	ADC_Channel_13,
	ADC_Channel_14,
	ADC_Channel_15
};

Before getting onto the advantages and disadvantages of enum’s, let’s have a quick review.

Read more »

%d bloggers like this: