Posts Tagged ‘c++

28
Aug
14

Interactive menus for UnitC++

UnitC++ has gone to version 1.1.0. The new feature is the addition of an interactive menu system. You run your tests declared using the TEST macro with the following code.

/=============================================================================
int main(int argc, char** argv)
{
  return UnitCpp::TestRegister::test_register().run_tests_interactive(
    argc,
    argv
  );
}

This will produce a menu which looks something like this;

================================================================================
0) All tests.

================================================================================
1) Maths
  2) "Maths:sqrt_results"
  3) "Maths:is_square"
  4) "Maths:sqrt_precondition"

================================================================================
5) MyString
  6) "MyString:length_test"
  7) "MyString:validity_test"

The numbers which you run the tests with can be input on the command line also, so utest.exe 0 will always run all of the tests.

See more at my sourceforge page

Advertisement
12
Aug
14

UnitC++ on SourceForge

My latest project, UnitC++ , is now live on SourceForge. Check it out here

07
Aug
14

Humour in the C++ standard

It’s nice to see that the C++ standard, while mostly dry, has a little humour in it. There is a limerick in section 14.7.3, 7. It goes like this;

When writing a specialization,
be careful about its location;
or to make it compile will be such a trial
as to kindle its self-immolation.

And according to Mostly Buggy in version C++0x FCD there was an amusing footnote in Section 29 Atomic operations library

29.1 General [atomics.general]
1 This Clause describes components for fine-grained atomic access. This access is provided via operations on atomic objects.341
[…]
341) Atomic objects are neither active nor radioactive.

But sadly in my copy (ISO IEC 14882) this was not included. It must have been taken out before the official standard was released.

There are according to Michael Wong two limericks in the standard, but I couldn’t find the second one (in the document, or on the internet).

29
Jul
14

UnitC++

This post is an introduction to a library I have written, UnitC++.

UnitC++ is a modern, light weight, header-only c++ library for making unit testing easy. The intention of this library is to make it really easy to test c++ code in a portable way.

 

Continue reading ‘UnitC++’

03
Mar
14

Functional Data Structures in C++: Lists

Great article by Bartosz Milewski. I’m always interested in applying different paradigms to C++. Here is my attempt at this.

  Bartosz Milewski's Programming Cafe

“Data structures in functional languages are immutable.”

What?! How can you write programs if you can’t mutate data? To an imperative programmer this sounds like anathema. “Are you telling me that I can’t change a value stored in a vector, delete a node in a tree, or push an element on a stack?” Well, yes and no. It’s all a matter of interpretation. When you give me a list and I give you back the same list with one more element, have I modified it or have I constructed a brand new list with the same elements plus one more?

Why would you care? Actually, you might care if you are still holding on to your original list. Has that list changed? In a functional language, the original data structure will remain unmodified! The version from before the modification persists — hence such data structures are called persistent (it has…

View original post 4,199 more words

08
Oct
13

C++ Digraphs

This is not as you might think, an article about implementing directed graphs in C++. The digraphs I am writing about are sequences of characters which act as a stand in for other characters. Digraphs and trigraphs exist in many languages, but I will be focusing on C++. The difference between digraphs and trigraphs is simple the number of characters, a digraph is 2 characters and a trigraph is 3 characters.

Digraphs are part of the language because in the past special characters were hard to input. This was generally because they were not on the keyboard, but in a few cases, they were not even in the code page!

So what use is this now, when modern keyboards have all the symbols we could want and we can use different encodings in source files?

Here is a screenshot of the C++ standard where it defines the allowed digraphs.

Digraphs in C++ Standard

C++ standard digraphs

The first column are backwards compatible digraphs for C. The next two columns are rather interesting.

For example. If you write the word or in a C++ source file, the compiler will replace that with ||. This means that the following code compiles and works.

//=============================================================================
int main() {
  bool a = false;
  bool b = true;
  std::cout << "a or b == " << (a or b) << std::endl;
  return 0;
}

Not only will this work for built in types, this works for user defined operators too. This is because the compiler simply substitutes the symbols.

Here is an example class and calling code which uses all the C++ digraphs.

Class

This is just a stub class which defines a lot of operators which do nothing.

//=============================================================================
class Example {
public:

  //===========================================================================
  // logic operators
  bool operator&&(const Example& t) {
    return true;
  }
  
  bool operator||(const Example& t) {
    return true;
  }
  
  bool operator!() {
    return true;
  }
  
  //===========================================================================
  // bitwise operators
  bool operator&(const Example& t) {
    return true;
  }
  
  bool operator|(const Example& t) {
    return true;
  }
  
  bool operator^(const Example& t) {
    return true;
  }
  
  bool operator~() {
    return true;
  }
  
  //===========================================================================
  // logic equals operators
  Example operator&=(const Example& t) {
    return t;
  }
  
  Example operator|=(const Example& t) {
    return t;
  }
  
  Example operator^=(const Example& t) {
    return t;
  }
  
  Example operator!=(const Example& t) {
    return t;
  }
  
};

Calling Code

//=============================================================================
int main() {
  bool a = true;
  bool b = true;
  if (a and b) {
    cout << "\"and\" is an operator." << endl;
  }
  if (false or b) {
    cout << "\"or\" is also an operator." << endl;
  }
  if (not false) {
    cout << "\"not\" is also an operator." << endl;
  }

  Example t_1, t_2;
  if (t_1 and t_2) {
    cout << "\"and\" even works for classes" << endl;
  }
  
  if (t_1 or t_2) {
    cout << "\"or\" even works for classes" << endl;
  }
  
  if (not t_1) {
    cout << "\"and\" even works for classes" << endl;
  }
  
  if (t_1 bitand t_2) {
    cout << "\"bitand\" also works for classes" << endl;
  }
  
  if (t_1 bitor t_2) {
    cout << "\"bitor\" even works for classes" << endl;
  }
  
  if (compl t_1) {
    cout << "\"compl\" even works for classes" << endl;
  }
  
  if (t_1 xor t_2) {
    cout << "\"xor\" even works for classes" << endl;
  }
  
  t_1 and_eq t_2;
  cout << "\"and_eq\" even works for classes" << endl;
  
  t_1 or_eq t_2;
  cout << "\"or_eq\" even works for classes" << endl;
  
  t_1 xor_eq t_2;
  cout << "\"xor_eq\" even works for classes" << endl;

  return 0;
}

This gives the output;

"and" is an operator.
"or" is also an operator.
"not" is also an operator.
"and" even works for classes
"or" even works for classes
"and" even works for classes
"bitand" also works for classes
"bitor" even works for classes
"compl" even works for classes
"xor" even works for classes
"and_eq" even works for classes
"or_eq" even works for classes
"xor_eq" even works for classes

This file can be found here.

This is an interesting feature, but is it useful?

I think it is, I think that the code;

if (not fail and ok) {
  // ...
}

Is more readable than;

if (!fail && ok) {
  // ...
}

However just because these are defined in the standard does not mean they can be used. These are largely considered a legacy part of the standard and there is limited support for it.

In particular Microsoft’s C++ compiler will not compile it. Both clang and g++ will compile it however, so if you are compiling using either of these you can use this nice feature.

Thanks for reading.

08
Apr
13

Comparisons in C++

This is about the comparison operators in C++ and making them easy to implement. There are 6 comparison operators in C++; ==, !=, <, <=, >, and >=. If you want to be able to apply all of these to a class, and you have the right type of order, you only need to implement one function which will determines them all. Incidentally this is called a total order, but I won’t go into what that means here.

The tl;dr of this is look at this repository and use a class from there to easily implement custom comparison operators.

This idea is to map the order onto the real numbers (doubles). So you have a function which takes two instances of a class and returns a double. If this function returns a negative number then the first instance is less than the second, if it returns 0 they are equal and if it returns a positive number then the first instance is greater than the second.

This will be easier to see with an example, so here is a class which is just data storage for an int.

Continue reading ‘Comparisons in C++’

25
Mar
13

C++ Sandbox

This is just a short post to tell you about my C++ sandbox. This is my area for trying out ideas (such as using mutable for caching) or testing C++ 11 features.

This is stored as a mercurial repository on bitbucket here. Please feel free to have a look or add to it if you have something you want to try out. I often use this to test answers to stackoverflow questions. A few of them have generated blog posts here as well.

The rest of this post is the current contents of the repository with a brief description of what I was trying to do with each file.

Arrays

In this file I was playing around with C style arrays, slightly old and a bit dated to be honest.

Comparisons

This may be a future post here. It defines a templatised base class for comparable class (using the curiously recurring template pattern . It means that if you inherit from this class and define one compare function, you get all 6 comparison operators.

ConstPointer

Testing out what you can do with const pointers. With a const Class* const you can only call const methods, with a Class* const you can call anything (this keeps the pointer const not what it points at) and with a Class* you can call anything.

Constness

Found an unusual bug and tested it here. If you have a reference (or a pointer) as a member of your class, in a const function you can call non-const functions on the member. This is because it doesn’t change the reference (or pointer) which the class keeps, what it does is change is the object it references.

CopyReference

Trying to copy a reference without using the copy constructor or assignment operator.

DivideByZero

I wondered what compiler errors/warnings you get from dividing by zero?
It turns out (in g++) that it will not give errors at all. It will warn you if you divide by a literal zero or a const zero, but not a variable with value zero.

ExclusiveOr

This was for checking the results of using xor on integers.

Lambda

This was testing the newly added lambda functions, but changed to using standard template library algorithms.

MustOverride

This was playing around with pure virtual functions with implementations. So you can call them using Base::function() in the derived class.

Mutable

Testing using a mutable member for data caching. This was the basis for the blog post mutable and data caching.

Operators

Testing calling operator() on pointer. Here is the calling code.

  Foo* f = new Foo();
  (*f)();
  (*f).operator()();
  f->operator()();

  delete f;

A common mistake doing this is to leave off the final brackets so.

  (*f).operator();
  f->operator();

But these will return a function pointer to operator(), they won’t call it.

Polygons

Archetypal polygon example for inheritance. A base polygon, a derived rectangle and triangle. Not great as you use a width and height for the polygon but not all polygons have it. Also I prepended all the classes with the letter C and allocated the instances as pointers to the base class.

SelfDeleting

Trying to make an executable to delete itself, unsurprisingly this doesn’t work.

SpareMemory

Something picked up from a dirty programming trick called the programming antihero (if you haven’t read that article I can’t recommend it enough!). In this there was a game programmer who reserved 2Mb of memory to lose later when memory was tight. I was testing to see how this worked by reserving some memory and checking memory usage. It is had to see the exact memory usage from this sort of thing due to differences in types of memory (i.e. private bytes/working set…) but it certainly took some memory.

StructClass

Testing out the differences between structs and classes in C++. I found that apart from private/public as default there is no difference! This includes if you declare class T in a template, you can still use a struct.

UserDefinedLiterals and UserDefinedLiteralsBinary

Trying to use C++ 11 user defined literals to be able to use syntax like this:

  Binary two = 10_b;

I was following a good guide from here.

VariadicPointerOffset

Quite a complicated file. I was trying to use variadic templates to access private methods of a class. Hopefully not of any practical use (it breaks encapsulation and is extremely fragile) but an interesting idea to try,

Windows

Unimplemented test for SetEvent() in windows.h.

get_env

Made to test getenv from cstdlib for getting environmental variables.

hashes

Using C preprocessor magic to join together variable names.

number_of_coins

Given an amount in cents (American currency as it was taken from an answer on stackoverflow) find the number of ways you can make it from quarters, dimes, nickles and pennies. This was taken from this answer.

stack_overflow_virtual

I didn’t think the reply to this question would compile so I tried it out. I realised you can override private virtual functions but not call them.

upper

My thoughts about the answer to this stackoverflow question being wrong, and my idea for a better way.

As always thanks for reading.

30
Oct
12

Auto

I don’t think this is widely known but auto was already a keyword in C++ and also C. Prior to it’s removal in C++09 it was used as a storage duration indicator. What this means is that it tells the compiler how long the storage for the variable needs to last for. The auto keyword is the default and means that the storage is available until the end of the block in which the variable is created. The fact that this is the default behaviour for C++ and it’s infrequent use lead to it being removed from the standard. As Bjarne Stroustrup writes

Several committee members trawled through millions of lines of code finding only a handful of uses — and most of those were in test suites or appeared to be bugs

So onto the new auto. Continue reading ‘Auto’

26
Oct
12

Mutable and Data Caching

This blog post is going to be about the c++ keyword mutable, it is also going to go into using mutable for data caching. To motivate this I am going to give an example from python. If I have a class with a property which is expensive to compute I want to cache it and only recalculate it when necessary. Continue reading ‘Mutable and Data Caching’




Call Me
Endorse davidcorne on Coderwall

Categories

Copyright


© 2013 by David Corne.

Creative Commons License

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.