Int-To-Type idiom

#include <iostream>
using namespace std;

template <int N>
class Array
{
    enum class InsertOp : int { NONE, INSERTION, QUICK };           // Three insert method to choose.

    template <InsertOp N>
    class IntToType {};                                             // Differenciate type by this class. 

    static constexpr enum InsertOp sc_op = N == 0 || N == 1 ? NONE :    // Here deduce which insert method should be used.
                                           N < 100 ? INSERTION : QUICK;

// other members...
public: // Interface. void sort() { sort(IntToType<sc_op>()); } // Call different insert method by type. private: // logic. void sort(IntToType<NONE>) { cout <<"no-op." <<endl; } void sort(IntToType<INSERTION>) { cout <<"insertion sort." <<endl; } void sort(IntToType<QUICK>) { cout <<"quick sort." <<endl; } }; int main(int argc, char *argv[]) { Array<1> t0; t1.sort(); // no-op. Array<10> t10; t10.sort(); // insertion sort. Array<100> t100; t100.sort(); // quick sort. return 0; }

 

  'class Array' is a fixed size array. We want to use sort algorithm on it, deduced by the number of element.

  Every 'Array<N>' with unique 'N' will create a different class, whose object will use "the best" sort method, that's to say: if number of element is zero or one, there is no reason to swap element, so no operation will occur; insertion sort will be used if between 2 and 100 sincing the better performance for little amount of element; for large quantity, quick insertion is the best chosen.

  The key of this trick is to use 'sc_op' to classify insertion into three method, and use 'class IntToType' to create different class by template and differenciate function call at compile-time. That's really cool.

 

posted @ 2012-09-20 14:47  walfud  阅读(185)  评论(0编辑  收藏  举报