Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

チュートリアル的な記述6

継承やテンプレートなどを色々使ってみた。

#include <iostream>

void hello() {
    std::cout << "hello/bye" << std::endl;
    
    std::string s;
    
    while (true) {
        std::cin >> s;

        if (s == "hello") {
            std::cout << "hello!" << std::endl;
        } else if (s == "bye") {
            std::cout << "bye!" << std::endl;
        } else {
            std::cout << "?" << std::endl;
        }
    }
}

class Name {
public:
    std::string name;
    Name(std::string name) {
        this->name = name;
    }
};

template <typename T>
class EchoSkill {
public:
    void echo(T x);
};

template <>
void EchoSkill<std::string>::echo(std::string x) {
    std::cout << "echo: " << x << std::endl;
}

template <>
void EchoSkill<int>::echo(int x) {
    std::cout << "echo int: " << x << std::endl;
}

class Counter : public Name, public EchoSkill<int>, public EchoSkill<std::string> {
public:
    Counter(std::string name) : Name(name) {
        
    }
    ~Counter(){}
    void count() {
        countNum++;
    }
    int getCount() {
        return countNum;
    }
private:
    int countNum = 0;
};

std::string question(std::string txt) {
    std::string s;
    std::cout << txt << std::endl;
    std::cin >> s;
    return s;
}

void hello2() {
    
    typedef std::shared_ptr<Counter> Counter_sptr;
    auto counter = std::make_shared<Counter>("hoge");
    
    while (true) {
        std::string s = question("hello/bye/repCount/name");
        
        if (s == "hello") {
            std::cout << "hello! " << counter->name <<"." << std::endl;
            counter->count();
        } else if (s == "bye") {
            counter->EchoSkill<std::string>::echo("bye!");
            break;
        } else if (s == "name") {
            counter->name = question("input name");
        } else if (s == "repCount") {
            counter->EchoSkill<int>::echo(counter->getCount());
        } else {
            std::cout << "?" << std::endl;
        }
    }
}