检查给定类型是否具有内部模板重新绑定 [英] Check if a given type has a inner template rebind

查看:207
本文介绍了检查给定类型是否具有内部模板重新绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个trait,它会检查一个给定的类型是否有一个名为 rebind 的内部模板,它需要一个模板类型参数。类似:

I need a trait which will check if a given type has an inner template named rebind which takes a single template type parameter. Something like:

template <typename X>
struct has_rebind
{
    static const bool value = /* ??? */;
};

这与 BOOST_TTI_HAS_TEMPLATE ,但是我想在不使用Boost TTI的情况下实现trait,我不会知道如何实现宏。

This is similar to what BOOST_TTI_HAS_TEMPLATE does, but I want to implement the trait without the use of Boost TTI, and I do not know how that macro is implemented.

推荐答案

C ++ 11和更高版本为我们提供了大量的替代方法,可以用相当简单的方式编写任意复杂类型的traits。其中之一是 void_t : / p>

C++11 and up gives us a wealth of alternatives with which to write arbitrarily complex type traits in fairly simple fashion. One such is void_t:

template <typename... >
using void_t = void;

你所做的就是写一个基本特征:

All you do is write a base trait:

template <typename X, typename = void>
struct has_rebind : std::false_type { };

,然后进行部分专业化,只有满足您所需的条件,才能通过模板扣除,即 X 有一个 rebind< T> 。在这种情况下,类型没有关系,所以我们可以选择一个:

and then a partial specialization that will only pass template deduction if the criteria you want is met, namely that X has a rebind<T>. In this case, the type doesn't matter, so we can just pick one:

template <typename X>
struct has_rebind<X, void_t<typename X::template rebind<int>>>
: std::true_type { };

Demo

同样的事情是 Yakk的 can_apply ,其中有一些样板: p>

A different approach to the same thing is Yakk's can_apply, which with some boilerplate:

namespace details {
  template<class...>struct voider{using type=void;};
  template<class...Ts>using void_t=typename voider<Ts...>::type;

  template<template<class...>class Z, class, class...Ts>
  struct can_apply:std::false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply=details::can_apply<Z,void,Ts...>;

我们可以写类似的:

template <typename X, typename T>
using rebind_t = typename X::template rebind<T>;

template <typename X>
using has_rebind = can_apply<rebind_t, X, int>;

演示2

这篇关于检查给定类型是否具有内部模板重新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆