C++ &引用;有条件的;别名模板

C++ &引用;有条件的;别名模板,c++,templates,template-meta-programming,sfinae,C++,Templates,Template Meta Programming,Sfinae,在非专用模板结构pointer\u traits(即template-struct-pointer\u traits)之类的类型中,存在一个成员别名模板rebind,该模板定义为Ptr::rebind,如果存在,或者其他类型。虽然我已经看到了一些关于检查某个成员是否存在的答案,但是如何实现像pointer\u traits::rebind这样的“有条件”别名模板呢?也就是说,好像通过以下伪C++: template <typename T> using type = has_type

在非专用模板结构
pointer\u traits
(即
template-struct-pointer\u traits
)之类的类型中,存在一个成员别名模板
rebind
,该模板定义为
Ptr::rebind
,如果存在,或者其他类型。虽然我已经看到了一些关于检查某个成员是否存在的答案,但是如何实现像
pointer\u traits::rebind
这样的“有条件”别名模板呢?也就是说,好像通过以下伪C++:

template <typename T> using type = has_type<T::U> ? int : float;
使用type=has\u type的模板?int:浮动; 或

template using type=if_有_type::type;

我考虑过使用类似于(检测成员类型部分)中描述的方法,但我不知道如何实现一个helper结构,它的[sole]成员类型取决于另一个成员类型的存在。

使用
std::conditional
from
。简单到:

using type = typename std::conditional<bool, int, float>::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
然后:

template<class Ptr>
struct pointer_traits
{
    using difference_type = typename detail::ptrait_diff_t<Ptr>::type;
};
模板
结构指针特性
{
使用difference\u type=typename detail::ptrait\u diff\u t::type;
};
检测到
的实现
可以找到。

这是设计用来解决的问题

#include <type_traits>
template<bool condition> 
using type = std::conditional_t<condition, int, float>;

static_assert(std::is_same<type<true>,  int>::value,   "type<true> should be int");
static_assert(std::is_same<type<false>, float>::value, "type<false> should be float");
#包括
模板
使用type=std::conditional\u t;
静态断言(std::is_same::value,“类型应为int”);
静态断言(std::is_same::value,“类型应该是float”);

我认为op更感兴趣的是条件的外观,而不是std::condition。
std::conditional
的实现似乎很容易理解,但是
是如何被检测到的?另外,尽管我是C++17新特性的粉丝,
pointer\u traits
是在C++11中实现的。如果不使用[实验性]C++17功能,您将如何实现此功能?@AliciaRose如果不使用[实验性]C++17功能,您将如何实现此功能?丑陋而痛苦。您可以在线查找标准库的源代码。“
std::is_detected
存在于C++17”否。“
使用差异类型=条件类型”
“双不”。在知道它存在之前,您无法尝试访问
typename Ptr::difference\u type
。如果您试图使用检测习惯用法,这是
detected\u或
的教科书用例,而不是
is\u detected
@T.C.对。谢谢你的注意。我没有试过这些。出于某种原因,我相信检测到的std::is_已被纳入标准。你每天都会失望。。。
template<class Ptr>
struct pointer_traits
{
    using difference_type = typename detail::ptrait_diff_t<Ptr>::type;
};
#include <type_traits>
template<bool condition> 
using type = std::conditional_t<condition, int, float>;

static_assert(std::is_same<type<true>,  int>::value,   "type<true> should be int");
static_assert(std::is_same<type<false>, float>::value, "type<false> should be float");