В С++ есть функции с переменным числом аргументов. Вот, printf, например
void printf(char* s, ...);
В C++0x теперь будут еще и шаблоны с переменным числом аргументов. В GCC они даже уже есть, в последних версиях, в рамках экспериментальной поддержки С++0x.
Пример, который обычно приводят, когда речь идет о шаблонах с переменным числом аргументов - type-safe printf().
void printf(constchar* s) {
while (*s) {
if (*s == '%' && *++s != '%')
throwstd::runtime_error("invalid format string: missing arguments");
std::cout << *s++;
}
}
template<typename T, typename... Args>
void printf(constchar* s, const T& value, const Args&... args) {
while (*s) {
if (*s == '%' && *++s != '%') {
// ignore the character that follows the '%': we already know the type!std::cout << value;
return printf(++s, args...);
}
std::cout << *s++;
}
throwstd::runtime error("extra arguments provided to printf");
}
Ещё их можно будет использовать, например, для кортежей с переменным числом элементов. То есть tuple<int, float> - кортеж с двумя элементами tuple<int, float, string> - кортеж с тремя элементами и т.д.
Кортежи и сейчас есть в boost, там они реализованы с помощью имеющихся средств.
Также шаблоны с переменным числом аргументов предоставляют интересные возможности для метапрограммирования шаблонов. То есть последователям Александресу есть где порезвиться ;-)
typedef - это не простая подстановка. Поэтому некоторые моменты, связанные с typedef'ом, могут удивить. Допустим, в коде объявлены какие-то такие переменные.
constchar* pX, Y, Z; //1
Через некоторое время мы решаем использовать typedef.
typedefchar* pChar; //2
И после этого переписываем первый кусок кода как
const pChar pX, Y, Z; //3
Что неправильно, потому что первый и третий код не эквивалентны. Третий код без typedef'а будет выглядеть так.
char * const pX, * const Y, * const Z;
Тут не только Y и Z совсем не того типа, которого хотелось, но и у pX const применен к самому указателю, а не к тому, на что тот указывает. Всё это потому, что здесь
const pChar pX, Y, Z;
мы объявили pX, Y и Z константами типа pChar, а это не эквивалентно замене char* другим словом.
Поэтому в winnt.h, есть typedef'ы как для неконстантных вариантов указателей, так и для константных.
typedefchar* LPSTR;
typedefconstchar* LPCSTR;
(реально там объявления более лохматые, но смысл такой)
В статье Const input parameters and typedefs нам советуют избегать typedef'ов для типов с указателями и использовать const только явно и когда он нужен.
Сотрудники CERN'а не остались равнодушными к весёлой истерии вокруг запуска Большого адронного коллайдра. Они написали Песнь о Коллайдре. В ролике на YouTube они пляшут на фоне интерьеров этого самого коллайдра и поют. Хорошо у них получается.
Ссылки по теме: How to destroy the Earth - сайт, на котором объясняется, что уничтожить Землю не так уж и просто...
Для тех, кто по каким-то причинам не может просмотреть видео, а так же для тех, кто любит петь хором на природе - текст песни (я его скопипастила с какого-то японского блога и исправила опечатки).
Large Hadron Rap (C)Alpinekat: Katherine McAlpine
Twenty-seven kilometers of tunnel underground, designed with mind to send protons around a circle that crosses through Swtizerland and France. Sixty nations contribute to scientific advance.
Two beams of protons swing 'round through the ring they ride 'til in the hearts of the detectors they're made to collide!
And all that energy packed in such a tiny bit of room becomes mass particles created from the vacuum And then....
LHCb sees where the antimatter's gone ALICE looks at collisions of lead ions CMS and ATLAS are two of a kind: They're looking for whatever new particles they can find
The LHC accelerates the protons and the lead, and the things that it discovers will rock you in the head.
We see asteroids and planets stars galore We know a black hole resides at each galaxy's core. But even all that matter cannot explain what holds all these stars together something else remains.
This dark matter interacts only through gravity And how do you catch a particle there's no way to see? take it back to consevation of energy, and the particles appear clear as can be
You see particles flyin' in jets they spray, but you notice there ain't nothin' goin' the other way.
You say, "My law has just been violated! That don't make sense! There's gotta be another particle to make this balance!"
And it might be dark matter and for the first time, we catch a glimpse of what must fill most of the known 'Verse Because...
LHCb sees where the antimatter's gone ALICE looks at collisions of lead ions. CMS and ATLAS are two of a kind They're looking for whatever new particles they can find.
Antimatter is sort of like matter's evil twin.
Because except for charge and handedness of spin, they're the same for a particle and its anti-self, but you can't store an anti-particle of any shelf.
Cuz when it meets its normal twin, they both annihilate. Matter turns to energy, and then, it dissipates.
When matter is created from energy, which is exactly what they'll do in the LHC, you get matter and antimatter in equalparts, and they try to take this back to when the universe starts: the Big Bang.
Back when all the matter exploded, But the amount of antimatter was somehow eroded! Because when we look around we see that matter abounds, but the antimatter's nowhere to be found. That's why....
LHCb sees where the antimatter's gone ALICE looks at collisions of lead ions. CMS and ATLAS are two of a kind: They're looking for whatever new particles they can find. The LHC accelerates the protons and the lead, and the things that it discovers will rock you in the head.
The Higgs boson, that's the one that everybody talks about, and it's the one sure thing that this machine will sort out. If the Higgs exists they ought to see it right away, And if it doesn't, the scientists will finally say,
"There is no Higgs! We need new physics to account for why things have mass." "Something in our Standard Model went awry!"
But the Higgs -- I still haven't said just what it does. They suppose that particles have mass because There is this Higgs field that extends through all space, and some particles slow down while other particles race straight through, like the photon it has no mass but something heavy like the top quark, it's draggin' its ---(!)
And the Higgs is a boson that carries a force, and makes particles take orders from the field that is its source. They'll detect it...
LHCb sees where the antimatter's gone ALICE looks at collisions of lead ions. CMS and ATLAS are two of a kind: They're looking for whatever new particles they can find.
Now some of you may think that gravity is strong, cuz when you fall off your bicycle, it don't take long Until you hit the earth, and you say,"Dang that hurt!"
But if you think the force is powerful, you're wrong. You see, gravity, it's weaker than weak! And the reason why is something many scientists seek.
They think about dimensions. We live in just three, but maybe there are others that are too small to see.
It's into these dimensions that gravity extends, which makes it seem weaker here on our end.
And these dimensions are rolled up, curled so tight that they don't affect you in your day-to-day life.
but if you were as tiny as a graviton, you could enter these dimensions and go wandering on. And they'd find you...
When LHCb sees where the antimatter's gone ALICE looks at collisions of lead ions. CMS and ATLAS are two of a kind: They're looking for whatever new particles they can find. The LHC accelerates the protons and the lead, and the things that it discovers will rock you in the head.
Systems built by unsupervised intermediate developers are going to fail for completely different reasons than systems built by juniors. A junior will build a big pile of algorithms that sort of work. A good intermediate will build pages out of “Design Patterns” and “Domain Driven Design”. While those are great books for learning how to build large OO systems, direct application of this sort of theory results in over engineered systems that are flexible in ways that don’t matter, and inflexible in ones that do matter