C++ std::tuple作为模板参数?
我正在尝试编写一个C++ std::tuple作为模板参数?,c++,templates,c++11,C++,Templates,C++11,我正在尝试编写一个std::sort模板比较类,该类应该接收未知数量的元组(可变模板)。每个元组应由一列(代码中的某种类型)和一个bool组成,指定该列是按升序还是降序排序 基本上,我想要类似的东西: // doesn't compile - conceptual code template <typename std::tuple<Col, bool>> struct Comparator { bool operator() (int lhs, int rhs)
std::sort
模板比较类,该类应该接收未知数量的元组(可变模板)。每个元组应由一列(代码中的某种类型)和一个bool组成,指定该列是按升序还是降序排序
基本上,我想要类似的东西:
// 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
}
}
//未编译-概念代码
模板
结构比较器
{
布尔运算符()
{
//lhs和RH是行索引。取决于列
//和收到的布尔值,决定哪个索引应该首先出现
}
}
这类事情可能在C++ 11中吗?< /p> < p>是的,可能的-你想要部分专门化<代码>比较器< /代码>:
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...>;
//用于检查类型是否为std::tuple格式的特征
模板
结构是_col_bool_tuple:false_type{};
模板
结构是_col_bool_tuple:true_type{};
//用于检查布尔包中的所有值是否为真的帮助器结构
模板结构文件包;
模板
使用all_true=std::is_same;
//用于检查类型列表是否都是std::tuple格式的特征
模板
使用are\u col\u bool\u tuples=all\u true;
//传递错误模板参数时的不完整类型
//因为可变参数必须是最后一个,所以需要这个impl助手
模板
结构比较mpl;
//当模板参数正确时,我们的专用实现
模板
结构比较器mpl
{
布尔运算符()
{
//你做比较吗
}
};
//一个不错的别名模板,用于将类型转发到SFINAE检查类模板
模板
使用比较器=比较器MPL;
@BaummitAugen,因为稍后我想添加基于列类型的模板专门化(应该提到)不应该操作符()
使用元组?这只能用于对整数进行排序…@Barry它对整数进行排序,但对于作为模板参数传递的列(整数表示行索引,列表示要排序的列),我不知道“关于列”是什么意思。你能举个例子吗?选民能否解释一下这有什么问题?也许我误解了这个问题?