Variadic int Template
-
Kann man die variadic Templates nicht auch für ints verwenden? Z.B. so
#include <iostream> template<int head, int ... tail> struct Accumulator { static const int result = head + Accumulator<tail...>::result; }; template<int head> struct Accumulator<head> { static const int result = head; }; int main() { std::cout << Accumulator<1,2,3,4,5>::result << std::endl; }
-
Also bei obigem Code heult G++ bei mir herum und spuckt folgende Meldung aus:
test.cpp:5:57: sorry, unimplemented: cannot expand ‘tail ...’ into a fixed-length argument list
-
welche gcc version verwendest du und hast du überhaupt den c++0x (bzw c++11) modus aktiviert?
-
4.6.3 und ich übersetze mit
g++ -pedantic -std=c++0x -W -Wall -o test test.cpp
-
#include <iostream> template< int... > struct Accumulator; template<int head, int ... tail> struct Accumulator< head , tail... > { static const int result = head + Accumulator<tail...>::result; }; template<int head> struct Accumulator<head> { static const int result = head; }; int main() { std::cout << Accumulator<1,2,3,4,5>::result << std::endl; }funktioniert bei mir.
Das Problem ist, denke ich, dass dein template nicht mit einem parameter pack anfängt, da es alstemplate<int head, int ... tail> struct Accumulator;deklariert wurde. Das parameter pack kann der gcc offensichtlich nicht in ein einzelnes Argument packen (wenn das template so deklariert wurde, bei Spezialisierung funktioniert es offensichtlich). Arbeite einfach mit dem workaround den ich gepostet habe.
-
Danke, damit klappt es!
Was ist ein parameter pack bzw. ein einziges? Sprich, mir ist das Problem nicht ganz klar, das du mit dem Workaround löst.
-
template< int... parameter_pack >Das ist ein parameter pack. Und beim gcc ist das nicht möglich:
template< int no_parameter_pack , int... > struct XY; XY< parameter_pack... > x;XY hat als erstes Argument kein parameter pack, man übergibt XY aber ein parameter pack. Eigentlich wäre das so möglich, indem das parameter pack aufgesplittet wird (vermutlich, wenn sich der gcc dafür entschuldigt), aber beim gcc wohl noch nicht. Das Problem scheint nur aufzutreten, wenn das template so deklariert wurde, d.h. parameter packs werden bei Spezialisierungen richtig aufgeteilt.
-
ok anscheinend ist diese syntax variante des variadic template im gcc 4.6 noch nicht implementiert. Ich kann deinen beispielcode mit clang version 3.2 (svn build) bauen.
Edit: mit gcc 4.7.0 funktioniert es auch.