在编译时比较两个整数序列?

And*_*dyG 2 c++ templates variadic-templates c++14

假设我有一个constexpr std::integer_sequence<...>对象.在编译时,我对它执行一些操作,然后我想static_assert它是==另一些std::integer_sequence<...>.鉴于这integer_sequence是一种类型,我如何提供一个constexpr bool operator==适当比较它们的重载 ?

一个更具体的例子:转换intstd::integer_sequence<char>.也就是说,将整数转换为字符序列(受到Peter Sommerlad在CPPCon '15的演讲的启发)

我有一些功能,我非常有信心将小于1000的十进制整数值适当地转换为4个元素的字符序列:

#include <utility> // integer_sequence

template<char... t>
using char_sequence = std::integer_sequence<char, t...>;
constexpr char make_digit_char(const size_t digit, const size_t power_of_ten=1, const char zero_replacement = ' ')
{
    return char(digit>=power_of_ten?digit/power_of_ten+'0':zero_replacement);
}

template<int num>
constexpr auto int_to_char_sequence()
{
    static_assert(num < 1000, "Cannot handle integers larger than 1000!");
    //format for up to 1000
    return char_sequence<' ', 
                    make_digit_char(num,100), 
                    make_digit_char(num%100,10,num>=100?'0':' '),
                    '0' + num % 10>{};
}
Run Code Online (Sandbox Code Playgroud)

但是,我不相信自己,所以我想写一些测试:

static_assert(char_sequence<' ', ' ', ' ', '0'>{} == int_to_char_sequence<0>(), "failed to convert 0 to char sequence");
static_assert(char_sequence<' ', ' ', ' ', '1'>{} == int_to_char_sequence<1>(), "failed to convert 1 to char sequence");
// ...
static_assert(char_sequence<' ', '1', '1', '1'>{} == int_to_char_sequence<111>(), "failed to convert 111 to char sequence")
Run Code Online (Sandbox Code Playgroud)

并且还要测试!=:

// ...
static_assert(char_sequence<' ', '1', '1', '1', '2'>{} != int_to_char_sequence<111>(), " 1 1 1 2 should not be equal to 111");
static_assert(int_to_char_sequence<111>() != char_sequence<' ', '1', '1', '1', '2'>{}, " 111 should not be equal to  1 1 1 2");
Run Code Online (Sandbox Code Playgroud)

所以我对等价运算符有一些要求:

  • 序列中的数据存储在类型中,因此两个字符序列基本上是不同的类型
  • 如果一个字符序列比另一个字符序列长?
  • 运营商需要constexpr这样static_assert才能发挥作用
    • 这意味着我们不能进行任何类型的转换std::array和比较

我该如何做到这一点?


作者注意:我没有找到关于SO的另一篇文章可以对整数序列进行编译时相等,所以我在下面回答了我自己的问题.这是我自己完成的工作,我绝不认为它是最佳方法.如果您有更好的方法,请将其作为另一个答案发布,我会接受它!

Bar*_*rry 9

这是一个较短的版本:

template <char... A, char... B>
constexpr bool operator==(char_sequence<A...>, char_sequence<B...>)
{
    return std::is_same<char_sequence<A...>, char_sequence<B...>>::value;
}
Run Code Online (Sandbox Code Playgroud)

当且仅当由这些序列组成的类型相同时,序列是相同的.


虽然通常情况下,您只需直接测试:

template <int num>
using int_to_char_sequence_t = decltype(int_to_char_sequence<num>());

static_assert(std::is_same<
    int_to_char_sequence_t<0>,
    char_sequence<' ', ' ', ' ', '0'>
    >::value, "!");
Run Code Online (Sandbox Code Playgroud)