22 Mart 2018 Perşembe

TypeErasure

Any Sınıfı
Şu satırı dahil ederiz.
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/relaxed.hpp>
Tanımlama
Şöyle yaparız.
namespace te = boost::type_erasure;

using my_any = te::any< boost::mpl::vector<
    te::copy_constructible<>,
    te::destructible<>,
    te::typeid_<>,
    te::relaxed
    /* I believe some changes here would do the trick */
    >>;
operator = metodu
Şöyle yaparız.
// Store an std::string by explicitly calling string constructor.
my_any a = string("abc");
any_cast metodu
Şöyle yaparız.
// Works as expected.
cout << te::any_cast<string>( a ) << endl;
BOOST_TYPE_ERASURE_MEMBER Macrosu
Runtime polymorphism olmadan metod kullanabilmeyi sağlar.
Örnek
Elimizde şöyle bir kod olsun.
#include <cassert>
#include <iostream>
#include <boost/concept_check.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/member.hpp>
#include <boost/type_erasure/free.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/mpl/vector.hpp>
using namespace std;

BOOST_TYPE_ERASURE_MEMBER((has_send), send)

using Connection = boost::type_erasure::any<
                        boost::mpl::vector<
                        has_send<void(const char*)>,
                        boost::type_erasure::copy_constructible<>>>;

BOOST_TYPE_ERASURE_MEMBER((has_make), make)

using ConnectionFactory = boost::type_erasure::any<
                        boost::mpl::vector<
                        has_make<Connection()>,
                        boost::type_erasure::copy_constructible<>,
                        boost::type_erasure::relaxed>>;
Bu metodları gerçekleştiren sınıflar ekleriz.
struct TcpConnection
{
    void send(const char* s) { cout << s << endl; }
};

struct UdpConnection
{
    void send(const char* s) { cout << s << endl; }
};

struct TcpConnectionFactory
{
    TcpConnection make() { return TcpConnection(); }
};

struct UdpConnectionFactory
{
    UdpConnection make() { return UdpConnection(); }
};
Şöyle yaparız.
template <class ConnFactory>
void send(ConnFactory& cf)
{
    Connection conn = cf.make();
    conn.send("hello");
}

int main(int argc, char* argv[])
{
    ConnectionFactory cf;
    if (argc > 1 && argv[1] == "tcp"s)
        cf = TcpConnectionFactory();
    else
        cf = UdpConnectionFactory();

    send(cf);
}


Hiç yorum yok:

Yorum Gönder