检查是否给定类型有一个内部的模板重新绑定 [英] Check if a given type has a inner template 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 = /* ??? */;
};
这是类似于<一个href=\"http://www.boost.org/doc/libs/1_54_0/libs/tti/doc/html/the_type_traits_introspection_library/tti_detail_has_template.html\"相对=nofollow> BOOST_TTI_HAS_TEMPLATE 做,但我想要实现在不使用升压TTI的特质,我不知道宏是如何实现的。
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及以上为我们提供了丰富的选择与编写任意复杂型性状相当简单时尚。一个这样的 void_t
:
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
有一个重新绑定&LT; T&GT;
。在这种情况下,该类型并不重要,所以我们可以随便挑之一:
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 { };
一个不同的方法做同一件事是 Yakk的 can_apply
,这与一些样板:
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...>;
我们可以写类似的东西:
We can write something similar:
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>;
这篇关于检查是否给定类型有一个内部的模板重新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!