【发布时间】:2017-01-12 11:21:12
【问题描述】:
我遇到了静态成员函数使用UNUSED 宏来消除编译器警告的问题。当宏生效时,它会导致 GCC 和 Clang 将函数拒绝为 constexpr。这是测试用例:
$ cat test.cxx
#include <iostream>
#include <stdint.h>
#define UNUSED(x) ((void)x)
template <unsigned int N>
class Foo
{
public:
enum {MIN_N=N}; enum {MAX_N=N}; enum {DEF_N=N};
constexpr static size_t GetValidN(size_t n)
{
UNUSED(n); return DEF_N;
}
};
class Bar : public Foo<16>
{
public:
Bar(size_t n) : m_n(GetValidN(n)) {}
size_t m_n;
};
int main(int argc, char* argv[])
{
Bar b(10);
return 0;
}
这是 GCC 错误消息:
$ g++ -std=c++11 test.cxx -o test.exe
test.cxx: In instantiation of ‘static constexpr size_t Foo<N>::GetValidN(size_t) [with unsigned int N = 16u; size_t = long unsigned int]’:
test.cxx:22:25: required from here
test.cxx:16:5: error: body of constexpr function ‘static constexpr size_t Foo<N>::GetValidN(size_t) [with unsigned int N = 16u; size_t = long unsigned int]’ not a return-statement
}
^
如果我删除 UNUSED 的使用,那么源文件将按预期编译:
constexpr static size_t GetValidN(size_t n)
{
return DEF_N;
}
据我所知,#define UNUSED(x) ((void)x) 是抑制 unused variable 警告的唯一可移植方式。我害怕删除UNUSED,因为宏在具有大量接口的非平凡C++ 项目中抑制了数千个警告。由于与审计和 C&A 相关的治理问题,我什至不确定是否可以删除 UNUSED。
如何使UNUSED 宏工作并与constexpr 配合使用?
Clang 会产生更有用的错误消息:
$ clang++ -std=c++11 test.cxx -o test.exe
test.cxx:15:2: warning: use of this statement in a constexpr function is a C++14
extension [-Wc++14-extensions]
UNUSED(n); return DEF_N;
^
test.cxx:4:19: note: expanded from macro 'UNUSED'
#define UNUSED(x) ((void)x)
^
1 warning generated.
从洁净室转移到生产时的另一个转折点:Doxygen。这更接近于实际发生的情况,因此我们不能省略变量名。
//! \brief Returns a valid N
//! \param n a value to determine a valid N
//! \returns a valid N
constexpr static size_t GetValidN(size_t n)
{
return DEF_N;
}
【问题讨论】:
-
可能是
return UNUSED(n), DEF_N;?无论如何,为什么这个函数需要n? -
@user2357112 - 它是一个接口的MCVE。真正的代码更有趣一点
标签: c++ c++11 constexpr unused-variables