Почему функция шаблона друга имеет различное поведение для структуры и класса?C++

Программы на C++. Форум разработчиков
Anonymous
Почему функция шаблона друга имеет различное поведение для структуры и класса?

Сообщение Anonymous »

Код: Выделить всё

#include 

template
requires (tc_n > 0)
struct StringLiteral final {
std::array value{};

consteval StringLiteral(char const (&sl)[tc_n]) {
for (auto i = std::size_t{}; i < tc_n; ++i) {
this->value[i] = sl[i];
}
}

template
friend consteval bool operator==(StringLiteral const& a,
StringLiteral const& b);
};

template
requires (tc_n > 0)
class StringLiteral2 final {
std::array value_{};

public:
consteval StringLiteral2(char const (&sl)[tc_n]) {
for (auto i = std::size_t{}; i < tc_n; ++i) {
this->value_[i] = sl[i];
}
}

template
friend consteval bool operator==(StringLiteral2 const& a,
StringLiteral2 const& b);
};

template
[[nodiscard]] consteval bool operator==(StringLiteral const& a,
StringLiteral const& b) {
return a.value == b.value;
}

template
[[nodiscard]] consteval bool operator==(StringLiteral2 const& a,
StringLiteral2 const& b) {
return a.value_ == b.value_;
}

template
constexpr auto operator""_sl() {
return tc_sl;
}

template
constexpr auto operator""_sl2() {
return tc_sl;
}

static_assert("hello"_sl == "hello"_sl);   // ok
static_assert("hello"_sl2 == "hello"_sl2); // error, why?

int main() {}
см. https://godbolt.org/z/ycgojkkmy, как GCC-15, так и Clang-20 Примите первое static_assert , но отвергайте второе. /> Почему функция шаблона друга имеет различное поведение для структуры и класса?

Подробнее здесь: https://stackoverflow.com/questions/796 ... uct-and-cl

Вернуться в «C++»