Category Archives: Programming

More interesting topics from ACCU 2013

  • Aleksander Fabijanic talked about Dynamic C++, with reference to rival approaches to representing dynamic types: boost::any, boost::variant, boost::type_erasure, Facebook folly::dynamic and poco::dynamic::var.
  • Stig Sandres presented a way to use boost::coroutines and std::future to emulate “await” from N3564.  This follows on from N3558, which includes the ability to add “.then(…)” to a std::future.
  • I hadn’t heard of reference-qualifiers, which C++11 allows you to put on a method declaration to restrict its use to either l-value or r-value references.  See this post on Stack Overflow.  In particular, there was a proposal to restrict standard library assignment operators to l-values (since it makes no sense to assign to an r-value reference).
  • Russell Winder used std::iota from the standard <numeric> library in an example to populate a container with sequentially increasing values
std::vector<int> elements(10);
std::iota( elements.begin(), elements.end(), 0 );
std::for_each( elements.begin(), elements.end(), 
    [] (int i){ std::cout << i; }); // prints 0123456789

Leave a comment

Filed under C++

Using std::tie to implement operator< (by Anthony Williams at ACCU 2013)

I’ve used std::tie to unbind the underlying data from a std::tuple in the past:

auto t = std::make_tuple( 1, 42, 100 );
int a, b, c;
std::tie( a, b, c ) = t;

But I hadn’t seen this handy trick for using std::tie to implement operator<

#include <tuple>

struct S
{
  S(int a_, int b_, int c_) : a(a_), b(b_), c(c_)
  {}

  int a;
  int b;
  int c;
};

bool operator<( const S& lhs, const S& rhs )
{
  return std::tie( lhs.a, lhs.b, lhs.c )
       < std::tie( rhs.a, rhs.b, rhs.c );
}

int main()
{
  S s1( 1, 2, 3), s2 ( 1, 2, 4 ), s3 ( 0, 2, 3);

  std::cout << "s1 should be less than s2: " << (s1 < s2) << "\n"
            << "s3 should be less than s1: " << (s3 < s1) << "\n";

  return 0;
}

Notice that std::tie does not copy the variables (as per the earlier example, it takes them by reference). You can also mimic the use of use of underscore in F#

let f i = (i, i*2, i*4)
let a, _, c = f 5

using std::ignore

auto f = []( int i){ return std::tuple(i, i*2, i*4); }
int a, b;
std::tie( a, std::ignore, b ) = f( 5 );

5 Comments

Filed under C++ Code

Examples of SFINAE (by Jonathan Wakely at ACCU 2013)

I’m currently attending ACCU2013 at Bristol and saw Jonathan Wakely’s presentation on SFINAE (Substitution Failure Is Not An Error) this morning.

This is a traditional SFINAE example using type traits.  true_type and false_type just need to have different sizes, then we can use function template specialization to differentiate between two cases.

typedef char true_type;
typedef double false_type;
template<class T>
true_type is_iter( typename T::iterator_category* t );
template<class T>
false_type is_iter(...);
template<class T>
struct is_iterator
{
  static const bool value =
    (sizeof(is_iter<T>(0)) == sizeof(true_type));
};

void testTypeTrait()
{
 std::cout
    << "Try int " << is_iterator<int>::value << "\n";
    << "Try vector<int>::iterator "
    << is_iterator<std::vector<int>::iterator>::value << "\n";
}

This example later in the presentation really stood out – a step towards Concepts, it shows syntax available today for restricting the types that will compile with a given template (thanks to C++11 aliasing and default arguments for template parameters):

class WidgetBase
{};

class Widget : public WidgetBase
{};

class Bodget
{};

class Decorator
{
private:
template<class T>
using IsDerivedWidget = typename std::enable_if<
        std::is_base_of<WidgetBase, T>::value>::type;

public:
template<class T,
class Requires = IsDerivedWidget<T>>
Decorator( const T& )
{}
};

So if I instantiate Decorator with Widget, it compiles (because Widget derives from WidgetBase), but instantiating with Bodget yields a compiler error (because Bodget does not inherit from WidgetBase).

Widget w;
Decorator decoratedWidget( w );
Bodget b;
Decorator decoratedBodget( b ); // Error

This code all compiles with recent versions of gcc (e.g. 4.7).  Under Visual Studio, only the traditional example compiles (default arguments for function templates are not yet supported, neither is aliasing, not even with the Nov ’12 CTP).

1 Comment

Filed under C++ Code

Beautiful Concurrency – Simon Peyton-Jones

This is a famous paper on concurrency and the benefits of functional programming. It’s obviously no coincidence that I’ve heard of the author in connection with F#.

For me, a beautiful program is one that is so simple and elegant that it obviously has no mistakes, rather than merely having no obvious mistakes

Simon claims that Haskell is the most beautiful language he knows, then introduces it via an example with side-effects, knowing that the result is quite ghastly to a newbie! He points out that

Being explicit about side effects reveals a good deal of useful information. Consider two functions:
f :: Int -> Int
g :: Int -> IO Int
From looking only at their types we can see that f is a pure function: it has no side effects. In contrast, g has side effects, and this is apparent in its type. Each time g is performed it may give a different result.

I got lost in the middle of the Santa example, but I get the sentiment behind the design:

Since there are no programmer-visible locks, the questions of which locks to take, and in which order, simply do not arise. In particular, blocking (retry) and choice (orElse), which are fundamentally non-modular when expressed using locks, are fully modular in STM.

Leave a comment

Filed under Programming

Benefits of functional programming

A couple of linked articles with a strong story on the benefits of choosing F# over C# for reducing the bug count and reducing the size of the codebase.

Simon Tyler Cousins compares two similar projects with F# clearly superior to C# in every category for those projects.

Don Syme opines that a key benefit of F# is that nulls are all but eliminated in the code and references the manifesto for Not Only O-O:

We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:

Functions and Types over classes
Purity over mutability
Composition over inheritance
Higher-order functions over method dispatch
Options over nulls

That is, while there is value in the items on the right (except for nulls), we value the items on the left more.

Leave a comment

Filed under Programming

GCC 4.8 released

GCC 4.8 has been released. This version uses C++ in its implementation (previously it was C only).

Leave a comment

Filed under C++

How to use smart pointers in C++

Good question about how to use c++ smart pointers posted on Stack Overflow. I haven’t used std::weak_ptr, but the idea of using it to return an “observing” pointer that you can later check for expiry and obtain a std::shared_ptr sounds like a better approach that returning a raw pointer.

Leave a comment

Filed under C++

WordPress App mangles my code!

I’ve noticed that whenever I use the WordPress App on my iPhone or iPad to edit a technical post that includes some code, the snippet I’ve carefully slaved over gets mangled. In particular, anything that uses templates in C++ (or generics in F#) will be affected, for example

vector<int> myData;

becomes

vector; myData;

The only answer at the moment is to be disciplined and restrict myself to editing code-based posts in the Web editor, which doesn’t destroy my content.

1 Comment

Filed under C++, Technology

Stephan Lavavej’s make_unique proposal

Stephan Lavavej has submitted a proposal to the C++ Standards committee for make_unique (the std::unique_ptr equivalent to std::make_shared for std::shared_ptr).

make_unique’s presence in the Standard Library will have several wonderful consequences. It will be possible to teach users “never say new/delete /new[]/delete[]” without disclaimers. Additionally, make_unique shares two advantages with make_shared (excluding the third advantage, increased efficiency). First, unique_ptr<LongTypeName> up(new LongTypeName(args)) must mention LongTypeName twice, while auto up = make_unique<LongTypeName>(args) mentions it once. Second, make_unique prevents the unspecified-evaluation-order leak triggered by expressions like foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y)). (Following the advice “never say new” is simpler than “never say new, unless you immediately give it to a named unique_ptr”.)

It’s a really useful utility as demonstrated in this video.

Leave a comment

Filed under C++

Equality and Comparisons in F#

This blog post from Don Syme is really useful when considering options for customising equality and comparisons in F#. Having said that, with F# 2.0, it looks like you don’t need to put attributes on your type, it’s enough to follow Don’s overrides of GetHashCode, Equals and CompareTo.

Leave a comment

Filed under Programming