C++ Class Templates

Sort by

recency

|

236 Discussions

|

  • + 0 comments
    template <class T>
    class AddElements{
        private:
        T element;
        public:
        AddElements(const T& t) : element(t) {}
        T add(const T& t){ return element + t;}
        T concatenate(const T& t){ return element + t;}
        
    };
    
  • + 0 comments

    include

    include

    include

    include

    include

    using namespace std;

    template class MyTemplate { T element1;

    public: MyTemplate(T num) : element1(num) {}

    T add(T element2) {
        return element1 + element2;
    }
    
    T concatenate(T element2) {
        return element1 + element2;
    }
    

    };

    int main() { std::ios_base::sync_with_stdio(false); int n ; cin >> n ; for(int i =0 ; i < n ; i++) {

        string select_type ;
        cin >> select_type ;
    
        if (select_type == "string") {
            string e1 ,e2 ;
            cin >> e1 >> e2 ;
            MyTemplate<string> m1(e1);
            cout << m1.concatenate(e2) << "\n";
        }
        else if ( select_type == "int" ){
            int e1,e2 ;
            cin >> e1 >> e2 ;
            MyTemplate<int> m1(e1);
            cout << m1.add(e2) << "\n";
        }
        else if ( select_type == "float" ) {
            double e1,e2 ;
            cin >> e1 >> e2 ;
            MyTemplate<double> m1(e1);
            cout << m1.add(e2) << "\n";
        }
    }
    
    return 0;
    

    }

  • + 0 comments
    /*Write the class AddElements here*/
    template <class T>
    class AddElements
    {
        T element;
    
    public:
        AddElements(const T &element)
        {
            this->element = element;
        }
    
        T add(const T &other)
        {
            return element + other;
        }
        T concatenate(const T &other)
        {
            return element + other;
        }
    };
    
  • + 0 comments

    Thank you gmharish285 for telling about c++11.

  • + 0 comments
    template <class T>
    class AddElements {
    private:
        T element;
    public:
        AddElements(const T& element) : element(element) {}
    
        T add(const T& other) {
            return element + other;
        }
    
        T concatenate(const T& other) {
            return element + other;
        }
    };