gpt4 book ai didi

c++ - MSVC 中的 Constexpr 友元函数

转载 作者:太空狗 更新时间:2023-10-29 23:10:47 25 4
gpt4 key购买 nike

我正在尝试在模板中定义 constexpr 友元运算符。尝试在非 constexpr 上下文中实例化此运算符时出现编译器错误。如果我将与模板类成员完全相同的运算符定义为自由模板函数,它可以正常工作。

template <typename T>
struct A
{
T Value;

// error
friend constexpr bool operator== (const A& l, const A& r)
{
return l.Value == r.Value;
}

// ok
constexpr bool operator!= (const A& r) const
{
return Value != r.Value;
}
};

// ok
template <typename T> constexpr bool
operator< (const A<T>& l, const A<T>& r)
{
return l.Value < r.Value;
}

#include <string>
int main ()
{
A<std::string> s;
bool ret = (s < s, s == s, s != s);
}

我得到的错误是

<source>(7): error C3615: constexpr function 'operator ==' cannot result in a constant expression

<source>(9): note: failure was caused by call of undefined function or one not declared 'constexpr'

<source>(9): note: see usage of 'std::operator =='

<source>(8): note: while compiling class template member function 'bool operator ==(const A<std::string> &,const A<std::string> &)'

<source>(29): note: see reference to class template instantiation 'A<std::string>' being compiled

Godbolt link

这种“ friend ”歧视是标准要求还是编译器错误?

最佳答案

[dcl.constexpr] 是这样说的:

If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is still a constexpr function or constexpr constructor, even though a call to such a function cannot appear in a constant expression.

所以用 std::string 实例化你的类模板是完全没问题的,你的比较函数仍然是 constexpr,虽然对它们的调用是不是 常量表达式(通过声明 ret constexpr 来检查)。标记这些函数 constexpr 根本不会给你带来任何好处(在这个实例化中),但它是完全合法的。

然后标准继续说

If no specialization of the template would satisfy the requirements for a constexpr function or constexpr constructor when considered as a non-template function or constructor, the template is ill-formed, no diagnostic required.

然而,这似乎不适用于您的情况,例如实例化内置类型确实满足 constexpr 要求。

MSVC 的编译错误似乎不无道理。它看起来像是编译器中的错误。

关于c++ - MSVC 中的 Constexpr 友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com