首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查从模板专门化派生出来的C++概念

检查从模板专门化派生出来的C++概念
EN

Stack Overflow用户
提问于 2021-11-26 22:51:07
回答 1查看 483关注 0票数 2

这就是答案这一提案中,我们可以看到std::is_specialization_of的实现(为方便起见包括在下面),它可以检测类型是否是给定模板的专门化。

代码语言:javascript
复制
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 {};

该建议明确指出,这种类型的特性不受继承的影响:

建议的特征只考虑专业化。因为专门化与继承无关,所以当任何模板参数都是通过继承定义时,特征的结果不受影响。

代码语言:javascript
复制
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说的

代码语言:javascript
复制
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>);

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

代码语言:javascript
复制
template<class, class> struct A{};
template<typename...>  struct B{};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-26 23:18:22

-fied rom MSVCSTL

代码语言:javascript
复制
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);
};

哪个我们使用它来实现只公开的类型特征。[range.view]/6的。

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

[演示]

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70130735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档