STD ::元组作为模板参数

std::tuple as template argument?

本文关键字:参数 元组 STD      更新时间:2023-10-16

我正在尝试编写一个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...>;