Zhongkun Ma
Zhongkun Ma

Reputation: 429

Restrictions for partial template specialization

Below is a simple example to learn meta-programming, which checks if the target type is contained by the variadic template arguments.

template<typename... Arguments> // Generic form
struct AnyOf;

template<typename Target, typename First, typename... Arguments>
struct AnyOf<Target, First, Arguments...> {
  constexpr static bool value = std::is_same<Target, First>::value || AnyOf<Target, Arguments...>::value;
};

template<typename Target, typename Last>
struct AnyOf<Target, Last> : std::false_type {
};

template<typename Target>
struct AnyOf<Target, Target> : std::true_type {
};

template<typename Target>
struct AnyOf<Target> : std::false_type {
};

The solution seems to work as expected, the implementation can be definitely improved.

There is one thing I do not understand, if the generic/primary form of template declaration is replaced by

template<typename Target, typename First, typename... Arguments>
struct AnyOf {
  constexpr static bool value = std::is_same<Target, First>::value || AnyOf<Target, Arguments...>::value;
};

The last partial specialization

template<typename Target>
struct AnyOf<Target> : std::false_type {
};

can't be compiled.

There are five restrictions summarized for partial template specialization at https://en.cppreference.com/w/cpp/language/partial_specialization, none of them seems applicable here.

Question: What is the restriction of partial template specialization to fail the compilation?

Upvotes: 5

Views: 174

Answers (1)

ecatmur
ecatmur

Reputation: 157484

This appears to be underspecified in the Standard; there is no explicit language that a partial specialization must actually match the primary.

However, the clause that "The partial specialization shall be more specialized than the primary template" ([temp.spec.partial.general]/9.2) would appear to apply, since the template argument list <typename Target> is not more specialized than template<typename Target, typename First, typename... Arguments>; if two template argument lists are not comparable under the specialization relation then certainly neither is more specialized than the other.

Upvotes: 3

Related Questions