http://anthony-arnold.com/2012/04/05/three-fun-cpp-techniques/

 

#include <iostream>
#include <string>
#include <memory>

class item
{
public :
    item():s("default"){}
private:
    std::string s ;
};

class location
{
public:
    location(std::string s_):s(s_){}
private:
    std::string s ;
};


template <typename T>
class teleporter_base {
public:
    void send_item(const item &i, const location &dest) {
        static_cast<T*>(this)->send_item_(i, dest);
    }

    item recv_item(const location &src) {
        return static_cast<T*>(this)->recv_item_(src);
    }
};
 
#ifdef MSVC
 
class win_teleporter : public teleporter_base<win_teleporter> {
public:
    void send_item_(const item &i, const location &dest) {
        std::cout << "win send_item_ called" << std::endl ;
    }
 
    item recv_item_(const location &src) {
        std::cout << "win recv_item_ called" << std::endl ;
    }
};
typedef win_teleporter teleporter_impl;

#else

class lin_teleporter : public teleporter_base<lin_teleporter> {
public:
    void send_item_(const item &i, const location &dest) {
        std::cout << "lin send_item_ called" << std::endl ;
    }

    item recv_item_(const location &src) {
        std::cout << "lin recv_item_ called" << std::endl ;
    }
};
typedef lin_teleporter teleporter_impl;
#endif

typedef teleporter_base<teleporter_impl> teleporter;

std::shared_ptr<teleporter> make_teleporter() {
    return std::make_shared<teleporter_impl>();
}

int main()
{
    auto tele = make_teleporter();

    tele->send_item(item(), location("my friend"));
    auto i = tele->recv_item(location("my other friend"));
}

g++ --std=c++0x main.cpp -o main.exe

lin send_item_ called
lin recv_item_ called

 

g++ --std=c++0x -DMSVC main.cpp -o main.exe

win send_item_ called
win recv_item_ called

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()