STD ::元组作为模板参数
std::tuple as template argument?
我正在尝试编写一个std::sort
模板比较应该接收未知数的元组(variadic模板)的类。每个元组都应由一列(我们在代码中具有某种类型)和一个布尔组成,并指定该列是否应按上升或降序进行排序。
基本上,我想要类似的东西:
// doesn't compile - conceptual code
template <typename std::tuple<Col, bool>>
struct Comparator
{
bool operator() (int lhs, int rhs)
{
// lhs and rhs are row indices. Depending on the columns
// and the bools received, decide which index should come first
}
}
在C 11中可以使用这种事情?
是的,这是可能的 - 您想要 Comparator
的部分专业化:
template <typename T>
struct Comparator;
template <typename Col>
struct Comparator<std::tuple<Col, bool>>
{
// ...
};
这是可能的吗?是的,但是您需要一些相当丑陋的模板技巧。
//a trait for checking if a type is of the form std::tuple<T,bool>
template <class Tuple>
struct is_col_bool_tuple : false_type{};
template <typename Col>
struct is_col_bool_tuple<std::tuple<Col,bool>> : true_type{};
//a helper struct for checking if all the values in a boolean pack are true
template<bool...> struct bool_pack;
template<bool... bs>
using all_true = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>;
//a trait to check if a list of types are all of the form std::tuple<T,bool>
template <class... Tuples>
using are_col_bool_tuples = all_true<is_col_bool_tuple<Tuples>::value...>;
//an incomplete type for when we pass incorrect template arguments
//this impl helper is needed because variadic parameters need to be last
template <typename Enable, class... Tuples>
struct ComparatorImpl;
//our specialized implementation for when the template arguments are correct
template <class... Tuples>
struct ComparatorImpl<std::enable_if_t<are_col_bool_tuples<Tuples...>::value>,
Tuples...>
{
bool operator() (int lhs, int rhs)
{
//do your comparison
}
};
//a nice alias template for forwarding our types to the SFINAE-checked class template
template <class... Tuples>
using Comparator = ComparatorImpl<void, Tuples...>;
相关文章:
- 将元组类型扩展为可变参数模板?
- 可变参数模板与使用元组在参数中添加不同的数据对
- 如何在可变参数模板函数中遍历可变参数元组?
- 创建派生自可变参数模板包的类型元组
- 如何在 c++ 中存储具有值的四个参数的元组
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 试图在C++14中将元组应用为参数
- 从函数的可变参数构建特定元组
- 将可变参数模板包装到元组向量
- 从函数返回元组时,将复制元组的参数,而不是移动元组参数
- 使用每种类型的可变参数模板上的类模板初始化元组
- C++ 从模板参数创建元组向量
- 如何从参数包构造引用的 std::元组?
- 有没有办法将一对元组剥离为可变参数模板类型或实例化具有可变参数类型的东西?
- 从可调用可变参数元组中的函数结果创建元组
- 返回元组的可变参数模板
- 当元组给出参数时,如何检查方法是否存在?
- 如何部分专业化功能以用元组元素作为参数调用功能
- 在 c++17 中解压缩可变参数元组
- 如何使用已知的非默认构造函数实例化未知大小的可变参数元组