5

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?

1
  • 1
    What's the minimum number of arguments accepted by the primary? Does the specialisation match that pattern, and is a special case of that? Commented Dec 27, 2021 at 23:26

1 Answer 1

3

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.

1
  • Thank you so much and I got it. Commented Dec 30, 2021 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.