“条件”别名模板

Mon*_*nad 4 c++ templates sfinae template-meta-programming

在像非专用模板struct pointer_traits(即template <class Ptr> struct pointer_traits)这样的类型中,存在一个成员别名模板rebind,该模板定义为Ptr::rebind<U>,如果存在,则为其他类型。尽管我在检查某个成员是否存在时看到了一些答案,但是如何实现一个“条件”别名模板,如pointer_traits::rebind?也就是说,就像通过以下伪C ++:

template <typename T> using type = has_type<T::U> ? int : float;
Run Code Online (Sandbox Code Playgroud)

要么

template <typename T> using type = if_has_type<T::U, int, float>::type;
Run Code Online (Sandbox Code Playgroud)

我考虑使用类似https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Member_Detector(“检测成员类型”一节)中描述的方法,但是我不知道如何实现其帮助结构[唯一]成员类型取决于另一个成员类型的存在。

Dei*_*Dei 6

通过使用std::conditionalfrom <type_traits>。就像这样简单:

using type = typename std::conditional<bool, int, float>::type;
Run Code Online (Sandbox Code Playgroud)

要么

using type = std::conditional_t<bool, int, float>;
Run Code Online (Sandbox Code Playgroud)

在这里bool用某种条件替换,可以在编译时将其评估为布尔值。在这种情况下,条件是检查现有成员。

如果条件为truetype,则成为type的别名int,否则为float

完整示例(检查是否difference_type为成员类型。)

namespace detail {

template<class Ptr>
using ptrait_diff = typename Ptr::difference_type;

template<class Ptr, bool = is_detected<ptrait_diff, Ptr>::value>
struct ptrait_diff_t { 
    using type = ptrdiff_t;
};

template<class Ptr>
struct ptrait_diff_t<Ptr, true> {
    using type = typename Ptr::difference_type;
};

} // namespace detail
Run Code Online (Sandbox Code Playgroud)

然后:

template<class Ptr>
struct pointer_traits
{
    using difference_type = typename detail::ptrait_diff_t<Ptr>::type;
};
Run Code Online (Sandbox Code Playgroud)

的执行is_detected可以在这里找到。