"Conditional"别名模板
"Conditional" alias templates
本文关键字:别名 Conditional 更新时间:2023-10-16
在像非专用模板结构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;
或
template <typename T> using type = if_has_type<T::U, int, float>::type;
我考虑使用类似于 https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Member_Detector 中描述的方法("检测成员类型"部分),但我不知道如何实现其 [唯一] 成员类型依赖于另一个成员类型的存在的帮助程序结构。
通过使用 <type_traits>
中的std::conditional
.它就像:
using type = typename std::conditional<bool, int, float>::type;
或
using type = std::conditional_t<bool, int, float>;
将bool
替换为某些条件,在编译时可评估为布尔值。在这种情况下,条件是对现有成员的检查。
如果条件为 true
则类型变为 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
然后:
template<class Ptr>
struct pointer_traits
{
using difference_type = typename detail::ptrait_diff_t<Ptr>::type;
};
is_detected
的实施可以在这里找到。
这就是 std::conditional 旨在解决的问题。
#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");
相关文章:
- 部分定义/别名模板模板参数
- 如何在C++20中创建模板别名的推导指南
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 告诉c++编译器该参数没有别名
- C++中是否存在 std::conditional 的懒惰等价物?
- boost::spirit::karma 替代生成器,带有 boost::variant 由字符串和字符串别名组成
- 继承模板类中的类型别名
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 为什么 GCC 在使用类型别名时处理 const reinterpret_cast不同?
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 为什么我们不能重复使用具有不同模板参数的别名模板标识符?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 如何使用类型别名从模板化类中隐藏模板列表
- 模板模板参数和模板别名:编译器错误?
- 使用定义函数模板别名
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- 为模板参数包添加别名
- 如何检测类型类型别名?
- C++类型别名,其中值被替换
- "Conditional"别名模板