下面是一个小测试用例,演示了我试图使用C++中的模板解决的问题:
template<typename T>
void
unused(T const &) {
/* Do nothing. */
}
int main() {
volatile bool x = false;
unused(!x); // type of "!x" is bool
}
Run Code Online (Sandbox Code Playgroud)
如下所示,g ++ v3.4.6编译器抱怨:
test.cc: In constructor `test::test()':
test.cc:11: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
test.cc:3: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
Run Code Online (Sandbox Code Playgroud)
这里的目标是在优化的代码中使用未使用的抑制未使用的变量警告.我有一个执行断言检查的宏,在优化代码中断言消失了,但是我希望断言表达式中的任何变量都保持引用,这样我才能在优化代码中得到未使用的变量警告.在unused()模板函数的定义中,我使用引用,以便不会无意中运行复制构造函数代码,以便编译器可以完全忽略对未使用的调用.
对于那些感兴趣的人,断言宏看起来像这样:
#ifdef NDEBUG
# define Assert(expression) unused(expression)
#else // not NDEBUG
# define Assert(expression) \
{ \
bool test = (expression); \
\
if (!test) { \
if (StopHere(__LINE__, __FILE__, __PRETTY_FUNCTION__, \
#expression, false)) { \
throw Exit(-1); /* So that destructors are run. */ \
} \
} \
}
#endif // else not NDEBUG
Run Code Online (Sandbox Code Playgroud)
对于上面的测试用例,我可以通过添加另一个类似的未使用函数来消除错误:
template<typename T>
void
unused(T const) {
/* Do nothing. */
}
Run Code Online (Sandbox Code Playgroud)
然而,当参数可以被引用时,其他调用unused()的情况由于模糊而失败,例如:
file.h:176: error: call of overloaded `unused(bool)' is ambiguous
myAssert.h:27: note: candidates are: void unused(T) [with T = bool]
myAssert.h:34: note: void unused(const T&) [with T = bool]
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何更改unused()或重载它以满足以下要求:
谢谢.
-威廉
正如约翰内斯在评论中所说,您遇到了编译器错误。您可以通过显式转换为来解决这个问题bool:
unused( bool( !readWriteActivated) ); // add bool() to any (!volatile_bool_var)
Run Code Online (Sandbox Code Playgroud)
如果我还记得 const-volatile 限定规则,那么您所需要的只是对虚拟变量进行更多限定。本质上,您只想将错误消息复制回声明的类型 :vP 中。
template<typename T>
void
unused(T const volatile &) { // only change is to add "volatile"
/* Do nothing. */
}
Run Code Online (Sandbox Code Playgroud)
另外,很高兴您将 放在const类型之后,它所属的位置。