Friday, December 23, 2011

Something about Template Specialization

When you have a generic template class,  some functionalities are not shared by all the data types and they are no needed for some specific data types. Template specialization just kicks in for this occasion. You can first declare a generic template for "all" the data types, then for a specific data type, you can provide a specific implementation. For example, if you want to implement a vector template, but you want to be space-efficient for bool type (e.g., use bit-vector to store them) other than some generic approach (e.g., use one integer to store one bool object). Then you can do as follow:

//generic template
template <typename T>
class vector
{
    // accessor functions and so forth
    private:
    T* vec_data;   // we'll store the data as block of dynamically allocated 
                   // memory
    int length;    // number of elements used 
    int vec_size;  // actual size of vec_data
};

//specialized
template <>
class vector <bool>
{
    // interface

    private:
    unsigned int *vector_data;
    int length;
    int size;
}; 


Besides, the interface for this specialized interface can be totally different from the generic template: they can have different methods. In some sense (or scenarios), template specialization can implement (substitute) the functionality of virtual inheritance. The major drawback of template specialization is increased code size and resulting complexity.

Similar to template specialization, we can also have partial specialization, which means you specialize certain features but still leave some feature for users to choose. The following shows one such example.

//generic template
template <typename T, unsigned length>
class fixedVector { ... };

//partial specialization
template <unsigned length>
class fixedVector <bool, length> { ... };


As we can see here, in the partial specialization,  the vector is determined to contain the bool type, but the length can still be specified.

Sunday, December 11, 2011

Two's Complement

Two's Complement is a system used to effectively represent negative integers such that we can treat the negative number as ordinary number and reuse the addition.

The problem arouses from One's Complement. For example, 2 is denoted as "00000010" and "-1" is denoted as "11111110" in One's Complement. Then naive way of doing "2 + (-1)" will get "00000000". That is incorrect. We need to further add a carry bit "1" to the sum. Then we can get "00000001", which is the right answer. However, we need to do an extra addition here.

In Two's Complement, the negative number is denoted by inverting all the bits in a positive number and adding 1. For example, "-1" is denoted as "11111111". Then we can just use the ordinary addition which save one extra addition. Besides, there is only one "0" in Two's Complement, but two in One's Complement (0 and -0).