I had asked the similar question before , understood that i can make it work by partially specialization. But to understand variadic templates basics i modified the code such like this.
template<typename T, typename... args>
struct counter{
static const int value= 1+ counter<args...>::value;
};
template<typename T>
struct counter<T>{
static const int value = 0;
};
error : “sorry, unimplemented: cannot expand ‘args …’ into a fixed-length argument list”
i understand this is bug and has been fixed in gcc 4.7.0
so to fix all this we have to use trick or whatever , which is partial specializing the template.
template<typename... Args> struct counter;
template<>
struct counter<> {
static const int value = 0;
};
template<typename T, typename... Args>
struct counter<T, Args...> {
static const int value = 1 + counter<Args...>::value;
};
Actual question: so I really want to know what special effect does partial specialization does here so that code works or I should ask how partial specialization resolves the issue? (why is it second version doesn’t hits the bug? ). Any explanation with motivation problem and examples will be very helpful.
The second version avoids the bug because the primary template is declared as
template<typename...>, i.e. it’s variadic. The key to the bug is in the error message: “sorry, unimplemented: cannot expand ‘args …’ into a fixed-length argument list” (emphasis mine).Thus
counter<Args...>::valuewill work on that second case becausecounteris tailored to accept any number of arguments. However, in the first case where the primary template is declared astemplate<typename T, typename... args>, the compiler has to separateargsinto a fixed-length part (T) and a variadic part (the newargs). Presumably that’s the very functionality that is not implemented in your version of GCC.I have no reason to believe that whatever machinery allows the
<T, Args...>specialization of the second case to match the<typename...>primary template could be reused for fixed-length expansion.(Finally since the support of C++11 features is marked as ‘experimental’ by GCC you really can’t have any expectation as to what will work and what won’t, much less why and how. Those kind of questions can only reasonably be answered by GCC developers on their mailing-list, not us. We’re not mind readers.)