std::tie for less comparison and char arrays

std::tie for less comparison and char arrays

我一直都知道要快速实现 class 的运算符<,最有效的最快方法是使用 std::tie.

例如

struct TestInt
{
int a = 0;
int b = 0;
};

TestInt first;
TestInt second(first);

bool aLess = std::tie( first.a, first.b)
  < std::tie(second.a, second.b);
bool bLess = std::tie( first.a, first.b)
  > std::tie(second.a, second.b);
EXPECT_EQ(aLess, false);
EXPECT_EQ(bLess, false);
EXPECT_EQ(aLess, bLess);

如果您使用另一个包含具有字符数组成员的结构,则同样不起作用 喜欢:

struct TieTestChar
  {
  char a[10];
  int b=0;
  TieTestChar() {strcpy(a, "test");}
  };

TieTestChar first;
TieTestChar second(first);

bool aLess = std::tie( first.a, first.b)
  < std::tie(second.a, second.b);
bool bLess = std::tie( first.a, first.b)
  > std::tie(second.a, second.b);
EXPECT_EQ(aLess, false);
EXPECT_EQ(bLess, false);
EXPECT_EQ(aLess, bLess);

我错过了什么?

[已编辑测试用例]

您可能会模仿 std::tie C 数组的特殊情况,

template <typename T>
struct my_ref
{
    using type = T&;
};

template <typename T, std::size_t N>
struct my_ref<T[N]>
{
    using type = my_span<T/*, N*/>; // std::span doesn't provide comparison operators
};

template <typename T>
using my_ref_t = typename my_ref<T>::type;

template <typename ... Ts>
std::tuple<my_ref_t<Ts>...> my_tie(const Ts&... args) { return {args...}; }