C++ Class Templates

Sort by

recency

|

233 Discussions

|

  • + 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;
        }
    };
    
  • + 2 comments

    If you are facing timeout issues, just use c++11

  • + 0 comments

    here's my solution with c++20:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    template <typename T>
    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);
        std::cin.tie(nullptr);
    
        int n;
        std::cin >> n;
    
        for (int i = 0; i < n; i++) {
            std::string type;
            std::cin >> type;
    
            if (type == "string") {
                std::string e1, e2;
                std::cin >> e1 >> e2;
    
                MyTemplate<std::string> mt1(e1);
                std::cout << mt1.concatenate(e2) << '\n';
            } else if (type == "int") {
                int e1, e2;
                std::cin >> e1 >> e2;
    
                MyTemplate<int> mt2(e1);
                std::cout << mt2.add(e2) << '\n';
            } else if (type == "float") {
                double e1, e2;
                std::cin >> e1 >> e2;
    
                MyTemplate<double> mt3(e1);
                std::cout << mt3.add(e2) << '\n';
            }
        }
    
        return 0;
    }
    
  • + 1 comment

    Move to C++20 and force std::cin with

        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
    
    template <class T> class AddElements {
        T data;
    public:
        AddElements(T value) : data(value) {}
    
        T add(T a) {
            data += a;
            return data;
        }
    };
    
    template <> class AddElements<string> {
    public:
        string s;
    
        AddElements(const string& value): s(value) {}
        AddElements(string&& value): s(std::move(value)) {}
    
        string concatenate(const string& a) {
            return s.append(a);
        }
    };