Tuesday, November 8, 2011

On variadic templates

GCC developers, February 2008:
We have implemented the complete specification of variadic templates in the GNU C++ compiler [8], which are available in GCC 4.3. The implementation itself was relatively straightforward in GCC, implying that this feature can be implemented in other C++ compilers without architectural changes. Our basic implementation approach involved adding flags to each kind of template parameter and each function parameter stating whether these parameters are in fact parameter packs.
...
Microsoft guys,  September 2011:
We've developed a new scheme for simulating variadic templates.  Previously in VC9 SP1 and VC10, we repeatedly included subheaders with macros defined differently each time, in order to stamp out overloads for 0, 1, 2, 3, etc. arguments.  (For example, included the internal subheader repeatedly, in order to stamp out make_shared(args, args, args).)  In VC11, the subheaders are gone.  Now we define variadic templates themselves as macros (with lots of backslash-continuations), then expand them with master macros.  This internal implementation change has some user-visible effects.  First, the code is more maintainable, easier to use (adding subheaders was a fair amount of work), and slightly less hideously unreadable.  This is what allowed us to easily implement variadic emplacement, and should make it easier to squash bugs in the future.  Second, it's harder to step into with the debugger (sorry!).  Third, pair's pair(piecewise_construct_t, tuple, tuple) constructor had "interesting" effects.  This requires N^2 overloads (if we support up to 10-tuples, that means 121 overloads, since empty tuples count here too).  We initially observed that this (spamming out so many pair-tuple overloads, plus all of the emplacement overloads) consumed a massive amount of memory during compilation, so as a workaround we reduced infinity.  In VC9 SP1 and VC10, infinity was 10 (i.e. "variadic" templates supported 0 to 10 arguments inclusive).  In the VC11 Developer Preview, infinity is 5 by default.  This got our compiler memory consumption back to what it was in VC10.  If you need more arguments (e.g. you had code compiling with VC9 SP1 or VC10 that used 6-tuples), there's an escape hatch.  You can define _VARIADIC_MAX project-wide between 5 and 10 inclusive (it defaults to 5).  Increasing it will make the compiler consume more memory, and may require you to use the /Zm option to reserve more space for PCHes.

Monday, October 31, 2011

Ещё один неплохой шрифт

Что-то осточертел мне Consolas. (А уж стандартные шрифты — и подавно.)
Решил порыться в инете и наткнулся на то, что вы видите справа:

Недостаток — нету bold. Но это компенсируется забавными 'e', 'g', 'j', а также прыгающими циферками :-)

Thursday, October 20, 2011

Оно работает o_O

Решил тут запилить паттерн Visitor с блэкдже использованием std::shared_ptr:
#include <memory>
#include <type_traits>

...

struct Node : public std::enable_shared_from_this<Node> {
    virtual ~Node() {}
    virtual void accept(Visitor&) = 0;
};

#define DEFINE_ACCEPT_METHOD \
    virtual void accept(Visitor& v) { \
        v.visit(std::static_pointer_cast<std::remove_pointer<decltype(this)>::type>(shared_from_this())); \
    }

struct SomeNode : public Node {  
    ...
   DEFINE_ACCEPT_METHOD;
    ...
};
Но на самом деле макросы - зло. В данном случае можно обойтись безо всякой магии, просто заюзав CRTP ещё раз:
template <class NodeType>                                                                                       
struct VisitableNode : public Node {
    virtual void accept(Visitor& v) {
        v.visit(std::static_pointer_cast<NodeType>(shared_from_this()));
    }
};

struct SomeNode : public VisitableNode<SomeNode> { 
    ... 
};

Sunday, September 4, 2011

визуализация ОДУ в Asymptote

Задали нам, понимаешь, изоклины порисовать на досуге. Ну вот какой уважающий себя программер будет подобной фигнёй вручную заниматься? И вспомнил я тут про Asymptote.
Несколько минут ковыряния в документации привели к следующему: для рисования поля направлений и интегральных кривых имеется модуль slopefield, а для рисования изоклин — модуль contour.

Ну и вот что получилось:
import contour;
import slopefield;
import graph; // чтобы оси нарисовать

settings.outformat = "png";
unitsize(2cm);

pair a = (-5, -5);
pair b = (5, 5);

limits(a, b); // картинка ограничена прямоугольником с углами в a и b
xaxis("$x$", EndArrow);
yaxis("$y$", EndArrow);

real f(real x, real y) { return  x^2 + y^2 - 1; }
real[] isoclines = map(new real(real x){return x*x;}, // анонимная функция применяется к
                     uniform(1, 10, 9)                // массиву {1,2,3,4,5,6,7,8,9,10}
                   ); 

add(slopefield(f, a, b));
draw(contour(f, a, b, isoclines), green);

currentpen = red + 1.5;             // 1.5 - толщина пера в bp (bp == 1/72 дюйма)
for (var i : uniform(-5, 5, 20)) {  // range-based for, так сказать
    draw(curve((i, i), f, a, b));
    draw(curve((0, i), f, a, b));
} 

Thursday, August 25, 2011

gсс 4.6+ и венда

Почитывая "C++ Concurrency in Action", осознал, что пользоваться установленной в универе MS VC++ 2010 буду неспособен. Во-первых, потому что в GCC 4.6+ уже реализовали порядка половины стандарта C++0x, включая атомарные типы, мьютексы, потоки и т.п. Во-вторых, потому что терпеть не могу проприетарщину.

Возможных решений вырисовывалось несколько:
  • Cygwin: преимущество перед прочими вариантами - gcc, vim и прочие привычные штуковины из мира UNIX в одном флаконе. Только вот в его репозиториях даже в experimental лежит лишь gcc 4.5. Фэйл. Нет, ну не совсем фэйл: можно было кое-как собрать свежий gcc из исходников. Однако, как выяснилось, у меня не настолько прямые руки...
  • Mingw-w64: форк полудохлого mingw. В разделе Automated builds можно скачать свежие сборки. Однако, чтобы заработали std::thread, std::mutex и тому подобные няшки, нужно, стоя на одной руке, почесать левой ногой за правым ухом. Я даже пробовал, но как-то не вышло :'-(
    (Точнее говоря, с помощью вот этого вот совета мне удалось заставить работать std::thread, но не std::mutex, без которого использовать многопоточность - тот ещё маразм. При попытке заюзать мьютексы g++ плевался чем-то вроде "error: there are no arguments to '__gthread_mutex_timedlock' that depend on a template parameter, so a declaration of '__gthread_mutex_timedlock' must be available")
  • И вот сегодня я внезапно наткнулся на вот это: http://code.google.com/p/mingw-builds/ Обсуждение сборок здесь. Все многопоточные фичи вроде работают. В общем, человеку под ником niXman - респект и уважуха :-)
    А поскольку everything just works, то и говорить особо не о чем. Единственное, что можно отметить: читайте "Description" на гуглокоде во избежание недоразумений. Например, в текущем snapshot-е GCC 4.7.0 для работы std::thread надо компилять сорцы с флагом -static.
  • Ещё, наверное, возможен вариант в виде Live USB с линухом. Однако ну его на фиг, ибо наш препод, как выяснилось в прошлом году, даже Vim/GVim ни разу не видел.
В итоге я, ясен пень, остановился на mingw-builds. И вам советую во избежание плясок с бубном)

Thursday, August 18, 2011

map::iterator: избавляемся от ->first и ->second

Решил тут в процессе изучения С++ старый свой код порефакторить. Попался такой вот кусочек:
typedef unordered_map<int,double> ColumnMap;
typedef ColumnMap::const_iterator ColumnMapIter;
...
for(ColumnMapIter it = row->begin(); it != row->end(); ++it) {
    ColumnMap *tmp = other -> rlist[it -> first];
    ColumnMapIter it_col = tmp -> find(col);
    if (it_col != tmp->end()) {
        val += (it -> second ) * (it_col -> second);
    }
}
Согласитесь, что в этих first и second чёрт ногу сломит. Однако в плюсах имеется такая редкоиспользуемая фича, как указатели на члены класса. Почитать про них можно, например, здесь: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=142
С их-то помощью и можно заменить first и second на что-нибудь более понятное.

Смотрите:
typedef unordered_map<int,double> ColumnMap;
typedef ColumnMap::const_iterator ColumnMapIter;
...
typedef ColumnMap::value_type ColumnMapPair;
const ColumnMapPair::first_type ColumnMapPair::* column = &ColumnMapPair::first;
ColumnMapPair::second_type ColumnMapPair::* value = &ColumnMapPair::second;
...
for(ColumnMapIter it = row->begin(); it != row->end(); ++it) {
    ColumnMap *tmp = other -> rlist[*it.*column];
    ColumnMapIter it_col = tmp -> find(col);
    if (it_col != tmp->end()) {
        val += (*it.*value) * (*it_col.*value);
    }
}

Sunday, August 14, 2011

занятненький подкаст

Рыская по Википедии, случайно наткнулся на skepticality.com. На данный момент это официальный подкаст журнала "Skeptic", выпускаемого организацией "The Skeptics Society".

Сейчас на сайте выложено 160+ выпусков на самые разнообразные темы. Между прочим, каждый из них снабжён пачкой ссылок для заинтересовавшихся затронутыми в нём топиками.
Короче, рекомендую всем желающим объективно воспринимать реальность :-)