#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.

 

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2021-08-14
  • 2021-10-22
  • 2022-01-19
  • 2021-09-27
  • 2022-02-01
  • 2022-01-02
猜你喜欢
  • 2021-08-26
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案