问题
Consider the following artificial example:
template <typename T, typename... Args>
struct A {
typedef T Type;
};
Using A
with 1 or more arguments works while using it with zero arguments fails as expected:
error: wrong number of template arguments (0, should be 1 or more)
Is it possible to make A
handle the case of zero template arguments defining A::Type
to int
if there are no arguments and to the first template argument if there are?
回答1:
First define the primary template as the most general case — which also includes zero argument:
template <typename... Args> //general : 0 or more
struct A { using Type = int; }
Then partially specialize it for 1 or more parameters as:
template <typename T, typename... Args> //special : 1 or more
struct A<T,Args...> { using Type = T; }
Once you have this specialization, the primary template would be used for zero-argument only!
Note that mathematically 1 or more is a special case of 0 or more — the latter is a more general case (not the other way round).
回答2:
You could just add a default to the first argument, no specializations necessary:
#include <type_traits>
template <typename T = int, typename... >
struct A {
using type = T;
};
int main() {
static_assert(std::is_same<A<>::type, int>::value, "");
static_assert(std::is_same<A<double, char>::type, double>::value, "");
}
来源:https://stackoverflow.com/questions/29879564/handling-zero-argument-variadic-template-in-c11