Thursday, 1 May 2014

Using function template default parameters to elegantly create SFINAE overloads

Having read Remastered enable_if, some implementation was left as an exercise for the reader.

The article explains how to make use of function template default parameters to elegantly create SFINAE overloads.

Below is my implementation.

#include <iostream>
#include <type_traits>

// true iff all conditions ::values are true
template <typename Head, typename... Tail>
struct all
{
    static constexpr bool value = Head::value && all<Tail...>::value;
};
template <typename Head>
struct all<Head>
{
    static constexpr bool value = Head::value;
};
//---------------------------------

// scoped enum to allow for differentiation between enable/disable
namespace detail { enum class enabler {}; }

template <typename... Condition>
using enable_if_t = typename std::enable_if<all<Condition...>::value, detail::enabler>::type;

template <typename... Condition>
using disable_if_t = typename std::enable_if<!all<Condition...>::value>::type;

//---------------------------------

// example function showing SFINAE overloads
template <typename T,
          enable_if_t< std::is_arithmetic<T>
                     , std::is_integral<T>
                     >...>
T twice(T t)
{
    return 2*t;
}
template <typename T,
          disable_if_t< std::is_arithmetic<T>
                      , std::is_integral<T>
                      >...>
T twice(T t)
{
    return t + t;
}
//---------------------------------

int main()
{
    std::cout << twice(5) << std::endl;
    std::cout << twice(std::string("Hello world")) << std::endl;
    return 0;
}

Read more here

Tuesday, 29 April 2014

Exiting recursive function templates without using helper class templates and partial specialisation

Contrived examples follow, but they serve to illustrate partial specialisation of class templates vs exiting recursive function templates using a branch.

The old way: use a helper class template, partially specialise it with the recursion exit case, and call a static function on this class template from a function template:

#include <iostream>

// helper class template
template<typename T, unsigned idx>
struct foo_impl
{
    static void fn(T t)
    {
        std::cout << t << " " << idx << std::endl;
        foo_impl<T, idx - 1>::fn(t); // recursively call fn
    }
};

// partial specialisation of helper class template for exit case
template<typename T>
struct foo_impl<T, 0>
{
    static void fn(T) {} // do nothing exit case
};

// function template which uses helper class templates
template<unsigned idx, typename T>
void foo(T t)
{
    foo_impl<T, idx>::fn(t);
}

int main()
{
    foo<5>("Hello world");
    return 0;
}

The new way: have the special case branch in the function template itself, and recursively call the function template from itself.

To prevent the compiler from barfing when instantiating the recursive path, the trick is to recursively call the function template with the same parameters for the special case. Even though this code path will never actually execute, it is needed so the compiler can parse the template.

#include <iostream>

template<unsigned idx, typename T>
void foo(T t)
{
    if (idx == 0) // special exit case
        return;
    std::cout << t << " " << idx << std::endl;

    // recursively call the function
    foo<idx - (idx ? 1 : 0)>(t); // note recursion returns itself in special exit case (code path will actually never be reached)
}

int main()
{
    foo<5>("Hello world");
    return 0;
}


Friday, 11 April 2014

Create a local git repo, a remote github repo and sync them from the command line

Create a local repo

follow the instructions here.

Install hub

# install dependencies
sudo apt-get install rake

# clone repo
cd /tmp
git clone https://github.com/github/hub.git

# install hub
cd hub
sudo rake install prefix=/usr/local

# alias git to hub
echo 'alias git=hub' >> ~/.bashrc
. !$

# check it works
git version
# expected output:
# git version 1.8.3.2
# hub version 1.12.0-6-g8150ddb

Create a remote repo on github

create a repo with the name of the current directory
git create -d "My description" 

# push to github
git push origin master


Monday, 31 March 2014

MEAN stack build system

MEAN stack build system

The MEAN stack is [M]ongo, [E]xpress, [A]ngular, [N]ode.
Back end:
The server is built using Express, which is built on top of Node.
The database used by the server is MongoDB.
Front end:
The client is built using Angular.
The less version of Bootstrap is used for CSS.
I use Yeoman and the angular-fullstack generator to generate my MEAN stack scaffold.
yo angular-fullstack [app]
Development tools:
npm is used for the server dependencies; these are listed in package.json
Bower is used for the client dependencies; these are listed in bower.json
Grunt is used for the build system. The configuration is stored in Gruntfile.js
The file system structure is as follows:
site/
  app/            # client source code 
  lib/            # server source code
  test/           # tests
  public/         # client production build destination
  Gruntfile.js    # Grunt configuration
  package.json    # server dependencies
  bower.json      # client dependencies
  server.js       # Express server entry-point
Grunt plugins:
grunt-bower-install:
When new dependencies are added with bower, grunt-bower-install will automatically inject their css and js into index.html.
In the grunt.initConfig block of Gruntfile.js:
'bower-install': {
    app: {
        html: '<%= yeoman.app %>/index.html',
        ignorePath: '<%= yeoman.app %>/'
    }
},
grunt-file-blocks:
When new front end components added in the source tree, grunt-file-blocks will automatically inject the javascript into index.html and the less into main.less.
In the grunt.initConfig block of Gruntfile.js:
fileblocks: {
    options: {
        removeFiles: true,
        templates: {
            less: '@import \'${file}\';'
        }
    },
    js: {
        src: 'app/index.html',
        blocks: {
            components: { cwd: 'app', src: 'components/**/*.js' }
        }
    },
    less: {
        src: 'app/css/main.less',
        blocks: {
            components: { cwd: 'app', src: 'components/**/*.less' }
        }
    }
},
Development workflow:
File are monitored for changes and the front or back end are reloaded as required.
nodemon and LiveReload are run concurrently:
In the grunt.initConfig block of Gruntfile.js:
concurrent: {
    dev: {
        tasks: ['nodemon', 'watch'],
        options: {
            logConcurrentOutput: true
        }
    }
},
Back end changes are monitored by nodemon. If a file required by the server is changed, node will be relaunched, restarting the server.
In the grunt.initConfig block of Gruntfile.js:
nodemon: {
    dev: {
        options: {
            file: 'server.js',
            ignoredFiles: ['app', 'test', 'node_modules'],
            watchedExtensions: ['js']
        }
    }
},
Front end changes are monitored by LiveReload. If a file required by the client is changed, assets will be rebuild (eg less converted to css) and the browser will be refreshed
In the grunt.initConfig block of Gruntfile.js:
watch: {
    app: {
        options: { livereload: true },
        files: [
            'app/index.*',
            'app/css/*',
            'app/components/**/*.js',
            'app/images/*'
        ]
    },
    less: {
        tasks: ['less'],
        files: ['app/css/main.less', 'app/components/**/*.less']
    }
},
less: {
    build: {
        files: { 'app/css/main.css': 'app/css/main.less' }
    }
}
This article is inspired by Shawn Dahlen’s post on the build system 4dashes uses.

Tuesday, 28 January 2014

Angular configuration - default http headers

Help prevent CSRF attacks by setting the X-Requested-By / X-Posted-By header

angular.module('myApp')
    .config(function($httpProvider) {
        $httpProvider.defaults.headers.common['X-Requested-By'] = 'myApp';
    });

angular.module('myApp')
    .config(function($httpProvider) {
        $httpProvider.defaults.headers.post['X-Posted-By'] = 'myApp';
    });

angular.module('myApp')
    .config(function($httpProvider) {
        $httpProvider.defaults.headers.put['X-Posted-By'] = 'myApp';
    });

Change the default headers at runtime:

$http.defaults.common['X-Auth'] = "foobar";

Security.StackExchange discussion

Monday, 27 January 2014

Angular directives - require

If we want to expose an API to other directives, we should require a controller on the directive.

We can bind a controller to the directive with require. Multiple controllers can be required by using an array of strings.

app.directive('foo', function() {
  return {
    require: 'bar',
  }
});

Link function

When a controller is required, it will be passed as the 4th argument to the link function:

app.directive('foo', function() {
  return {
    require: 'bar',
    link: function (scope, element, attrs, bar) {
    }
  }
});

When multiple controllers are required, they will be passed as an array to the link function:

app.directive('foo', function() {
  return {
    require: ['bar, baz'],
    link: function (scope, element, attrs, controllers) {
      var bar = controllers[0];
      var baz = controllers[1];
    }
  }
});

Controller location

We can control where the controller can be found by prefixing the controller name as follows:

no prefix

The required controller must be specified on the directive itself. An exception is thrown if no controller is found.

?

Make the controller optional - if it is not found in the directive provided, null is passed as the 4th argument to
the link function.

ˆ

Walk up the parent chain until the controller is found



Combine the previous two options - walk up the parent chain until the controller is found, and pass null if none is found


Wednesday, 22 January 2014

Angular directives - isolate scope

If you don't want a directive to use its parent's scope, create isolate scope:

app.directive("widget", function() {
    return {
        scope : {},    // creates isolate scope
        ...
}

When using isolate scope, obtain access to the parent scope by binding some members:

app.directive("widget", function() {
    return {
        scope : {
            foo: '@' // binds to parent's $scope.foo
        },
        ...
}

3 bindings to parent scope exist:

    '@': 1-way, by value, as a string (updates in the directive are not propagated to the parent scope)
    '=': 2-way, by reference (updates in the directive will update the parent scope)
    '&': expression (the expression is executed in the context of the parent scope)

1-way binding:

app.directive("widget", function() {
    return {
        restrict: 'E', // can only be used as an element
        scope: {
            foo: '@'   // imports $scope.foo by value
        },
        link: function(scope, element, attrs) {
            // do something with attrs.foo
        }


<widget foo="blah"></widget>

In the directive's link function, attrs.foo === "blah".

Model expressions can be parsed too:

<widget foo="{{ model }}"></widget>

In the directive's link function, attrs.foo is a string containing the value in $scope.model.

2-way binding:

app.directive("widget", function() {
    return {
        restrict: 'E', // can only be used as an element
        scope: {
            foo: '='   // imports $scope.foo by reference
        },
        link: function(scope, element, attrs) {
            // do something with attrs.foo
        }


<widget foo="bar"></widget>

In the directive's link function, attrs.foo === $scope.bar. Updating attrs.foo will result in $scope.bar being updated too.

expression binding:

app.directive("widget", function() {
    return {
        restrict: 'E', // can only be used as an element
        scope: {
            foo: '&'   // foo() executed as expression on $scope
        },
        link: function(scope, element, attrs) {
            // attrs.foo() will execute the expression
        }


<widget foo="bar()"></widget>

In the directive's link function, attrs.foo() will execute $scope.bar()

pass parameters to expression:

Special syntax is required to pass parameters to the expression.

In the directive, foo({p1: val}) will pass val to expression foo, which is function bar(p1) on $scope