【问题标题】:C++ concept to check for derived from template specialization用于检查从模板专业化派生的 C++ 概念
【发布时间】:2022-01-04 21:19:16
【问题描述】:

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

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

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

提案明确指出这种类型特征不受继承影响:

提议的特征只考虑专业化。由于特化与继承无关,因此当任何模板参数碰巧通过继承定义时,特征的结果不受影响。

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_from,但Base 可能是给定模板的任何特化?比如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>);

它还应该支持具有多个参数的模板和/或参数包:

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

【问题讨论】:

    标签: c++ templates c++-concepts


    【解决方案1】:

    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 来自 [range.view]/6

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

    [DEMO]

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2014-09-23
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多