【发布时间】:2021-10-01 14:36:18
【问题描述】:
一些编译器(Intel icc、pgi/nvc++)对如下函数发出“缺少返回语句”警告,而其他编译器(gcc、clang)即使使用-Wall -Wextra -pedantic也不会发出警告:
下面的代码按照标准合法吗?
这是给出警告的我的代码的最小可重现示例。将其简化为,例如,仅使用一个函数即可消除警告。
// test.cpp
#include <climits>
#include <cstddef>
template<class T, std::size_t N>
class Test
{
public:
class Inner;
private:
static constexpr std::size_t NB_ = sizeof(std::size_t) * CHAR_BIT;
static constexpr std::size_t NI_ = (N + NB_ - 1) / NB_;
};
template<class T, std::size_t N>
class Test<T, N>::Inner
{
public:
Inner() : b_{0}, j_{0} {}
friend bool operator!= (Inner x, Inner y)
{
if constexpr(J_ > 0)
return x.j_ != y.j_ || x.b_ != y.b_;
else
return x.b_ != y.b_;
}
private:
static constexpr std::size_t J_ = NI_ - 1;
std::size_t b_;
std::size_t j_;
};
int main()
{
Test<int, 50>::Inner x, y;
int a, b;
x.b_ = a; y.b_ = b;
x != y;
}
编译:
> nvc++ test.cpp -std=c++17
"test.cpp", line 30: warning: missing return statement at end of non-void function "operator!="
}
^
detected during instantiation of class "Test<T, N>::Inner [with T=int, N=50UL]" at line 41
【问题讨论】:
-
来自 nvc++ 的错误警告,gcc/clang/msvc 不会发出警告。
标签: c++ c++17 language-lawyer