c++templatespartial-specialization

Content of class method determined by the template value


By using c++ 14 or c++11, do we have an elegant approach to do the following task? Number of members and type of operations are determined by the template input value 'count'

    template<int count>
    class show{
    public:
        run(){
            if (count == 1){
                int x;
            } else if(count ==2){
                int x, y;
            }else if(count ==3){
                int x, y, z;
            } 

            if (count == 1){
                printf("res: %d \n", x);
            } else if(count ==2){
                printf("res: %d \n", x+y);
            }else if(count ==3){
                printf("res: %d \n", x+y+z);
            } 

        }
    };

Update: can we use partial specialization or something related to the template in this case?


Solution

  • Yes, you can use specialization:

    template<int count>
    class show;
    
    template<>
    class show<1>{
        int x;
        public:
        show(int _x):x{_x}{}
        void run(){
            std::cout << "val of x " << x << std::endl;
        }   
    };
    
    
    
    template<>
    class show<2>{
        int x,y;
        public:
        show(int _x, int _y):x{_x}, y{_y}{}
        void run(){
            std::cout << "add " << x+y << std::endl;
        }   
    };
    

    But you also can have it more generic:

    template <int count>
    class simply
    {
        std::array<int, count> arr;
    
        public:
        template < typename ... T > 
            simply( T ... in ): arr{ in... } {}
    
        void run()
        {   
            std::cout << [this](){ int sum=0; for( auto el: arr ){ sum+=el; } return sum; }() << std::endl;
        }   
    };
    

    To use all the stuff above:

    int main() {
        show<1> s1(10);
        show<2> s2(100,200);
    
        s1.run();
        s2.run();
    
        simply<4> si( 1,2,3,4 );
        si.run();
    }
    

    Remarks: You should add some more stuff to simply to check that all parameters of type int with sfinae or static_assert. But his is another question ...