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?
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) .
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, "");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.