compile and run cpp program from vim

To compile and run cpp program from MVIM(or VIM) directly. Add this to your ~/.vimrc

1
2
nnoremap <C-c> :!g++ -o  %:r.out % -std=c++11<Enter>
nnoremap <C-x> :!./%:r.out

Note: You can remove/add the <Enter> if you prefer to press <Enter> yourself.

Now simply hit Ctrl + c to compile and Ctrl + x to execute.

For a source file with name main.cpp, commands will be expanded to

1
2
g++ -o main.out main.cpp -std=c++11
./main.out

The %:r gets the current filename without the extension whereas % gets the current filename.

You can very easily extend above approach to compile using makefile.

learning concept checking the hard way - part 3

In the previous posts this and this, I talked about the basics of concept checking and stuff you need to know.

Finally here’s our has_less method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#import <complex>

using namespace std;

template <typename T, typename unused = decltype(T() < T())>
std::true_type has_less_helper(const T&);

template <typename T>
std::false_type has_less_helper(...);

template <typename T>
constexpr bool has_less(void){
    using my_type = decltype(has_less_helper<T>(std::declval<T>()));
    return my_type::value;
}

template <typename T>
class BinarySearchTree{
public:
    static_assert(has_less<T>(), "Assertion failed. No less than operation defined.");
    BinarySearchTree() {
    }
};

int main(int argc, const char * argv[])
{
    BinarySearchTree<int> binarySearchTree;
    // compile time error here. since complex<int> doesn't have a '<' operator
    BinarySearchTree<complex<int>> compBinarySearchTree;
    return 0;
}

Let’s dissect the above method and see what’s happening.

has_helper method has two possible overload options. For the int datatype both are possible overload candidates but as we saw earlier compiler prefers the non-variadic option. So it choosses the first option which has a return type of std::true_type.

However for complex<int>, compiler has only one option since < doesn’t exist for complex type.

1
2
3
4
5
6
7
8
9
10
11
12
// we don't need to define the methods
// Since we are not calling them.
// we are just using the principle of SFINAE that applies to template
// arguments and not to the body

template <typename T, typename unused = decltype(T() < T())>
std::true_type has_less_helper(const T&);

//and

template <typename T>
std::false_type has_less_helper(...);

Note: true_type and false_type are just structs with values as true and false resp. Check out their usage

We could directly use has_less_helper to know what Type has a less than operator defined for it. However it is important to note that the has_less_helper assumes that type T has a default constructor defined for it(decltype(T() < T())).

To remove above dependency we could use declvalue(as discussed in previous post). That is what we are doing in has_less method.

1
2
3
4
5
6
7
template <typename T>
constexpr bool has_less(void){
    // using is equivalent to typedef
    using my_type = decltype(has_less_helper<T>(std::declval<T>()));
    // note that the return type is either true_type or false_type
    return my_type::value;
}

Note: the constexpr keyword makes the method evaluate at compile time. So we will have a true or false value from this method at compile time.

Inside our definition of generic BinarySearchTree we put a static_assert(compile time assert) to check that we have a less that operator define for the type T.

1
2
3
4
5
6
7
template <typename T>
class BinarySearchTree{
public:
    static_assert(has_less<T>(), "Assertion failed. No less than operation defined.");
    BinarySearchTree() {
    }
};

That’s it! Now when you declare something like

1
BinarySearchTree< complex<int> > compBinarySearchTree;

we get a compile time error.

Awesome! Now you understand the concept of concept checking. Happy coding.

learning concept checking the hard way - part 2

In the previous post, I talked about importance/use case of concept checking. In this post we’ll step by step see how concept checking works.

Our final goal is to write a has_less method, which for any given type will return true or false based on whether < is defined for that type or not at the compile time

Let’s first look at some of the c++ concepts which we’ll use in the process.

1. decltype

(since c++11)

decltype let’s you extract type from any expression. It’s available in C++11

For example, In the example below, decltype can be used to get the type of variable myType1 and used to define another variable with the same type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//dec.cpp file
class MyType{
public:
    MyType(){std::cout << "Mytype: constructor called." << std::endl; }
};

int main(int argc, const char * argv[])
{
    MyType myType1;
    decltype(myType1) myType2;
    return 0;
}

>> ./a.out
Mytype: constructor called.
Mytype: constructor called.

Takeaway: we can use decltype to get type of a variable.

2. declval

(since c++11)

declval creates a default constructed type of its argument for use in type checking. It never returns a value. It is usually used with decltype to determine the type of an expression. It doesn’t require constructor of the types to exist or match. Line 14 won’t compile because there is no matching constructor.

Note that the compilation error occurs because NonDefault type doesn’t have a “default” constructor. If you uncomment the line number 6, the compilation error on line 14 will go away since now compiler will find a matching constructor.

Example, taken from cpp reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Default {
    int foo() const {return 1;}
};

struct NonDefault {
//    NonDefault(){}
    NonDefault(const NonDefault&) {}
    int foo() const {return 1;}
};

int main()
{
    decltype(Default().foo()) n1 = 1; // int n1
//  decltype(NonDefault().foo()) n2 = n1; // will not compile
    decltype(std::declval<NonDefault>().foo()) n2 = n1; // int n2
    std::cout << "n2 = " << n2 << '\n';
}

3. constexpr

(since c++11)

constexpr gives you a constant at the compile time instead of runtime constant that you get using const keyword.

1
2
constexpr int CreateConstant (int a, int b) { return a * b; }
const int arraySize = CreateConstant(2,3);

arraySize will be calculated at the compile time here.

4. static_assert

(since c++11)

Performs compile-time assertion checking

1
2
3
4
5
6
//will give you a compile time assertion failure error. 
int main(int argc, const char * argv[])
{
    static_assert(1==2, "Assertion failed.");
    return 0;
}

5. Template specialization

Templates in c++ are turing complete and you can do lot of cool stuff with them. Some trivia about templates:

  • Templates are instantiated at compile time and only if they are used somewhere in a program. However they are checked for syntax.

    Consider the example below, where we have a generic template method(hello(T a)) that calls a method(iDontExist) that is not defined anywhere. However the code compiles successfully since we are not calling that method.

    Note the specialization of the template for int type. When compiler has more than one functions with the same name, it looks at the type and select the best match. In case of hello<int>(2), it selects the specialized template over generic so, it instantiates only the specialized template which is both syntactically and semantically correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// This is a valid code and will compile just fine
template <typename T>
void hello(typename T::foo a){
    int b = T::iDontExist(12); //iDontExist doesn't exist.
    std::cout << a << std::endl;
}

// Another possible candidate.
template <typename T>
void hello(T a){
    std::cout << a << std::endl;
}

int main(int argc, const char * argv[]){
    hello<int>(2);
    return 0;
}
  • Substitution failure is not an error (SFINAE)

Note in the above program, when hello<int> is called compiler first tries to match it with the void hello(typename T::foo a), however int doesn’t have a nested type int::foo. This is called a substitution failure, compiler failed to substitute typename T for int.

Compiler doesn’t throw a compilation error here; it removes this overload from potential candidate and tries to find the next possible match. If one or more candidates remain and overload resolution succeeds, the invocation is well-formed. Check out more about SFINANE on wikipedia

  • Given two possible candidates where one is variadic and other is not. Compiler always chooses the non-variadic method. For example, In the example below compiler has two candidates for hello<int>. Compiler chooses the non-variadic one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
// Note the variadic(...) arguments
void hello(...){
    std::cout << "variadic method." << std::endl;
}
// Another possible candidate.
template <typename T>
void hello(T a){
    std::cout << "non-variadic method." << std::endl;
}
int main(int argc, const char * argv[]){
    hello<int>(2);
    return 0;
}
>> ./a.out
non-variadic method.

That’s all we need and in the next post we’ll write our has_less method.

learning concept checking the hard way - part 1

What is a concept in C++?

A concept is a set of requirements (valid expressions, associated types, semantic invariants, complexity guarantees, etc.) that a type must fulfill to be correctly used as arguments in a call to a generic algorithm

For example if you write your own generic implementation for BinarySearchTree. It should basically work for any type for which < operator is defined. As long as you have that condition satisfied you can build a binary search tree for that type. For instance, < is defined for int, double. However it’s not defined for complex numbers. C++ has no explicit mechanism for representing concepts.

Consider the following possible way you may write your generic Binary Search Tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>

template <typename T>
class BinarySearchTree{
    public:
    // dummy method to insert a new node to the tree
    void insert(T value, T parent){
        // calling `<` operator. Compilation will fail if it doesn't exist
        // for a type.
        if(value < parent){
            std::cout << "Less than operator exists" << std::endl;
            //insert to the left of binary tree.
        }
    }
};

int main(int argc, char* argv[]){
    // instantiating template with int
    BinarySearchTree<int> bint;
    bint.insert(1,2);
    // instantiating template with double
    BinarySearchTree<double> bdouble;
    bdouble.insert(1.23,3.13);

    return 0;
}
1
2
3
4
>> g++ b.cpp -o btree
>> ./btree
Less than operator exists
Less than operator exists

Awesome, so it works for both doube and int, since < is defined for them. What happens if you try it with complex numbers? let’s see:

1
2
3
4
5
6
7
//include the complex lib
#include <complex>

// In main function
// instantiating template with complex
BinarySearchTree<std::complex<int> > bcomplex;
bcomplex.insert(std::complex<int>(1,2), std::complex<int>(4,5));

If you try to run your BinarySearchTree implementation for complex numbers you will get a compile time error. So the question is how do you check if a class has a certain method defined or not. Above Example is a trivial example to show you the use case, the error could be buried deep into your code and may not represent the actual reason for failure. Boost documentation gives a good example .

In short it would be good to have a has_less method for a generic type that determines if the given type has a < method defined or not. Using this method you can give your user a more meaningful error.

Note that you can use concept checking provided by boost library. You’d need to do something like this:

1
2
3
4
#include <boost/concept_check.hpp>

//inside class
BOOST_CLASS_REQUIRE(T, boost, LessThanComparableConcept);

For more info: visit http://www.boost.org/doc/libs/1_55_0/libs/concept_check/using_concept_check.htm

In the next post, we’ll implement our own short version of concept checking. It involves some really cool template tricks and C++ trivia.

Feel free to comment and give suggestions.

References:

  1. http://www.boost.org/doc/libs/1_55_0/libs/concept_check/concept_check.htm

star in ruby

I have seen the Ruby’s * operator used at several places in different ways and often times I get confused the way it is used. Finally I decided to learn more about it and here are few interesting roles of * operator that I found in Ruby. It can be used to multiply, repeat, copy or as a splat operator.


Multiplication

This is the most obvious role of *. It’s the multiplication operator. 2 * 2 = 4

Or an instance method of Fixnum class to perform multiplication. 2.*(2) = 4

Read on →

elasticsearch basics - Analyzers

Elasticsearch is a powerful open source search engine build over Apache Lucene. You can do all kind of customized searches on huge amount of data by creating customized indexes. This post gives an overview of Analysis module of elasticsearch.

Analyzers basically helps you in analyzing your data.:o You need to analyze data while creating indexes and while searching. You could analyze your analyzers using Analyze Api provided by elasticsearch.

Creating indexes mainly involves three steps:

  • Pre-processing of raw text using char filters . This may be used to strip html tags, or you may define your custom mapping. (Couldn’t find a way to test this using analyse api. Please put it in comments if you know some way to test these through Analyze Api)

Example: You could use a char-filter of type html_strip to strip out html tags.

A text like this:

1
<p> Learn Something New Today! which is <b>always</b> fun </p>

would get converted to:

1
Learn Something New Today! which is always fun
Read on →

modularize_sinatra - modular sinatra app generator

Sinatra is simple, small and fast.

Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort. – sinatra readme

The only downside is that it doesn’t offer you the typical “MVC” like Rails.

Lot of times Rails is an overkill for a simple application and Sinatra seems like a perfect choice. Since using Sinatra, you could write all your code in a single file, and at one time it becomes really hard to manage the code and you may feel the need of porting it to a framework like Rails. However, you don’t need all the features that comes with Rails. What you need here is some kind of modularization in your application. For this very purpose I created a gem called modularize_sinatra

modularize_sinatra creates a Rails like MVC structure without the overhead.

modularize_sinatra is available on rubygems. For installation and usage instructions please visit http://github.com/goyalankit/modularize_sinatra

Read on →

Initial commit

This is my first post. Through this blog, I hope to share technical, non-technical, all kind of stuff that I discover and/or create.