用于检查派生自模板专业化的 C++ 概念

C++ concept to check for derived from template specialization

and this proposal 中,我们可以看到 std::is_specialization_of 的实现(为方便起见包含在下面),它可以检测类型是否是给定模板的特化。

template< class T, template<class...> class Primary >
struct is_specialization_of : std::false_type {};

template< template<class...> class Primary, class... Args >
struct is_specialization_of< Primary<Args...>, Primary> : std::true_type {};

该提案明确表示此类型特征不受继承影响:

The proposed trait considers only specialization. Since specialization is unrelated to inheritance, the trait’s result is unaffected when any template argument happens to be defined via inheritance.

template< class > struct B { };
template< class T > struct D : B<T> { };

static_assert(     is_specialization_of_v< B<int>, B> );
static_assert(     is_specialization_of_v< D<int>, D> );

static_assert( not is_specialization_of_v< B<int>, D> );
static_assert( not is_specialization_of_v< D<int>, B> );

有没有一种方法可以实现 确实 考虑继承的东西,表现得像 std::derived_fromBase 可以是给定模板?比如,说 std::derived_from_specialization_of:

template<class>   struct A {};
template<class T> struct B : A<T> {};
template<class T> struct C : B<T> {};

static_assert(derived_from_specialization_of< A<int>, A>);
static_assert(derived_from_specialization_of< B<int>, B>);
static_assert(derived_from_specialization_of< C<int>, C>);

static_assert(derived_from_specialization_of< B<int>, A>);
static_assert(derived_from_specialization_of< C<int>, B>);
static_assert(derived_from_specialization_of< C<int>, A>);

应该也支持多参数模板,and/or参数包:

template<class, class> struct A{};
template<typename...>  struct B{};

De-_Ugly-fied rom MSVCSTL:

template <template <class...> class Template, class... Args>
void derived_from_specialization_impl(const Template<Args...>&);

template <class T, template <class...> class Template>
concept derived_from_specialization_of = requires(const T& t) {
    derived_from_specialization_impl<Template>(t);
};

其中 we use to implement the exposition-only type trait is-derived-from-view-interface from [range.view]/6.

请注意,这与 OP 中引用的 is_specialization_of 特征具有相同的限制:它仅适用于具有所有类型参数的模板。

[DEMO]