C++ Class Templates

  • + 4 comments

    Sharing my solution here :)

    template <class T> class AddElements {
        public:
            T element;
            AddElements(T i) {element = i;}
            T add(T i) {return element+i;}
        private:
            
    };
    template <> class AddElements <string> {
        public:
            string element;
            AddElements(string i) {element = i;}
            string concatenate(string element2) {return element+element2;}
        private:
            
    };
    
    • + 2 comments

      I thought you're suppose to write a add() function with no input arguments?

      • + 0 comments

        Why? Under any condition there is always an input argument for add.

      • + 0 comments

        I think the specification was that it doesn't take in the first element as an input, but you'd still need to take in the second as done above.

    • + 1 comment

      why AddElements {} is defined again. writing concatenate in first class will work efficiently

      • + 1 comment

        Because 2 types of i are different. Any thoughts of fixing that?

        • + 0 comments

          what does template specialization do? i dont quite get it

    • [deleted]
      + 4 comments

      too many lines. this works as well:

      template <class T> class AddElements {
          public:
              T element;
              AddElements(T i) {
                  element = i;
              }
              T add(T i) {
                  return element+i;
              }
              T concatenate(T i) {
                  return element+i;
              }
      };
      
      • + 1 comment

        thanks for sharing,helped a lot.

        • + 0 comments

          why making data member public?

      • + 0 comments

        Test Case 8 and 9 did not pass for me..Anyone else?

      • + 0 comments

        Time limit tast case failed

      • + 0 comments

        I have written similar code but mine is showing "Terminated due to Timeout"

    • + 0 comments

      Your got is correct but it takes more than 4 seconds as mention in the problem......so u have to find the better solution