среда, 18 ноября 2015 г.

Variant в C++

Класс, принимающий любые типы
стырено отсюда http://insidecpp.ru/patterns/variant/


#include <memory>
#include <string>

class variant
{
public:

    template <class T>
    variant& operator = (T const& t)
    {
        typedef type<T> assign_type;
        object = std::auto_ptr<assign_type>(new assign_type(t));
        return *this;
    }

    template <class T>
    operator T ()
    {
        typedef type<T> assign_type;
        assign_type& type = dynamic_cast<assign_type&>(*object);
        return type.get();
    }

private:

    class base
    {
    public:

        virtual ~base() {}
    };

    typedef std::auto_ptr<base> base_ptr;

    template <class T>
    class type : public base
    {
    public:

        type(T const& t)
        : object(t)
        {
        }

        T get() const
        {
            return object;
        }

    private:

        T object;
    };

    base_ptr object;
};

struct dummy
{
    int a;
    int b;
    int c;
};

int main()
{
    variant v1, v2, v3, v4;

    v1 = 2;
    v2 = 5.0f;
    v3 = std::string("Pot of gold");
    v4 = dummy();

    int         i = v1;
    float       f = v2;
    std::string s = v3;
    dummy       d = v4;

    return 0;
}

среда, 11 ноября 2015 г.

ProtoBuf - гугловская замена XML

ProtoBuf - бинарный XML

https://developers.google.com/protocol-buffers/docs/cpptutorial
http://knzsoft.blogspot.com.by/2012/11/protobuf.html

понедельник, 7 сентября 2015 г.

Управление завершением работы

Функция atexit(void (*)()) служит для этих целей. Она будет вызвана призавершении программы.
В этой функции можно почистить указатели, закрыть файлы, сокеты и т.д.

четверг, 3 сентября 2015 г.

Перегрузка на основе целого числа

#include <iostream>
using namespace std;

template<bool val>
class Int2Type {
public:
    enum {value=val};
};

template <class T,int size>
class A {

    static void Do(Int2Type<false>) {
        cout << "false";
    }
   
    static void Do(Int2Type<true>) {
        cout << "true";
    }
   
public:       
    static void Do() {
        Do(Int2Type<sizeof(T)==size>());
    }
};


int main() {
    // your code goes here
    A<int,2>::Do();
    return 0;
}

вторник, 1 сентября 2015 г.

среда, 19 августа 2015 г.

среда, 5 августа 2015 г.

Шаблон с переменным количеством параметров

#include <iostream>
using namespace std;

template <class T>
void print(T t) {
    cout << t;   
}

template <class T,class... Args>
void print(T t,Args... args) {
    cout << t << " ";
    print(args...);
   
}

int main() {
   
    print(5,"333",5.2);
    return 0;
}

c++

Обзор с++11 от Страуструпа: ссыль

generate(vec.begin(),vec.end(),[](){srand(clock());return rand()%10;}); remove_copy_if(vec.begin(),vec.end(),back_inserter(res),[](int i){return i>2;}); copy(vec.begin(),vec.end(),ostream_iterator<int>(cout," "));
copy(res.begin(),res.end(),ostream_iterator<int>(cout," "));

среда, 13 мая 2015 г.

Вложенность произвольных контейнеров

#include <iostream>
#include <vector>
#include <list>
#include <deque>
using namespace std;

template <class T>
struct inCount{
    enum {result = 0};  
};

template<class T,template <class TT,class alloc = allocator<TT> > class CON>
struct inCount<CON<T> > {
    enum {result = inCount<T>::result +1};
};

template <class T>
int foo(T const & t) {
    return inCount<T>::result;
}

int main() {
    // your code goes here
    vector< vector< list<vector <list<deque<int> > > > > > v;
  
    cout << foo(v);
    return 0;
}

Узнать вложенность вектора

#include <iostream>
#include <vector>
using namespace std;

template <class T>
struct inCount{
    enum {result = 0};   
};

template<class T>
struct inCount<vector<T> > {
    enum {result = inCount<T>::result +1};
};

template <class T>
int foo(T const & t) {
    return inCount<T>::result;
}

int main() {
    // your code goes here
    vector< vector< vector<int> > > v;
   
    cout << foo(v);
    return 0;
}

вторник, 24 марта 2015 г.

Проверить, является ли тип абстрактным

#include <iostream>
using namespace std;

template <class T>
class is_abstr {

typedef char yes[1];
typedef char no[2];

template <class C> static no& test(C (*)[1]);
template <class> static yes& test(...);
   
public:   
    static const bool value = sizeof(test<T>(0 )) == sizeof(yes);

};

class A {
public:
    virtual int foo() = 0;
   
};

class B : public A {
public:
    int foo() {cout << "foo";}

};


int main() {
    cout.setf(ios::boolalpha);
    cout << is_abstr<B>::value;
    return 0;
}