Processing a variational pattern with a null argument in C ++ 11

Consider the following artificial example:

template <typename T, typename... Args>
struct A {
  typedef T Type;
};

Using Awith 1 or more arguments works when using it with zero arguments, as expected:

error: incorrect number of template arguments (0, must be 1 or more)

Is it possible to do the Aprocessing of the arguments of the zero template, defining A::Type- intif there are no arguments and the first argument of the template, if any?

+4
source share
2 answers

First define the primary pattern as the most common case - which also includes a null argument:

template <typename... Args>            //general : 0 or more 
struct A { using Type = int; }

1 :

template <typename T, typename... Args> //special : 1 or more
struct A<T,Args...>  { using Type = T; }

!

, 1 0 β€” - ( ).

+8

, :

#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, "");
}
+5

Source: https://habr.com/ru/post/1584752/


All Articles