C ++ Clang发出有关未使用的模板变量的警告 [英] C++ Clang emit warning about unused template variable

查看:99
本文介绍了C ++ Clang发出有关未使用的模板变量的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个未使用的模板变量定义,例如:

Considering an unused template variable definition, such as this one :

template <typename T, typename = void>
struct is_complete : std::false_type {};
template <typename T>
struct is_complete<T, std::void_t<decltype(sizeof(T))>>
    : std::true_type {};
template <typename T>
constexpr static inline auto is_complete_v = is_complete<T>::value;

在这里,Clang发出有关未使用的 is_complete_v 变量的警告,这对我来说似乎是错误的.
如果未使用,为什么会完全实例化这样的可变符号?也许我遗漏了一点.

Here, Clang emit a warning about unused is_complete_v variable, which seems wrong to me.
Why would such variable symbol be instanciated at all, if unused ? Perhaps I'm missing a point.

warning: unused variable 'is_complete_v' [-Wunused-const-variable]
    static inline constexpr auto is_complete_v = is_complete_v<T>::value;
           

情况是,其他编译器(例如GCC)不会发出任何警告.
哪个IMOO产生了感觉,因为该符号未解析.

The case is, other compiliers like GCC does not emit any warning.
Which IMOO makes sens, as the symbol is not resolved.

我可以使用以下任一方法修复我正在使用的所有代码库:

I could fix up all the codebases I'm working with using either :

template <typename T>
#if __clang__
[[maybe_unused]]
#endif
constexpr static inline auto is_complete_v = is_complete<T>::value;

或通过禁用 -Wunused-const-variable

但是我不知道:

  • 有没有更清洁的方法来实现这一目标?
  • 这是正常现象吗?

推荐答案

不使用" Clang的启发式诊断类似乎根本不检查每个实例,而是检查未实例化的模板本身.

The heuristics for the Clang "unused" class of diagnostics don't appear to inspect each instantiation at all, but rather the uninstantiated template itself.

我本人也遇到过类似的问题,特别是在依赖模板函数中的构造函数产生副作用(针对RAII等)时.当Clang需要知道传递的模板参数以确定所使用的构造函数时,它会天真地将构造函数视为纯函数,并将构造的变量标记为未使用( Wunused-variable ),但是如果构造函数可以在不实例化模板的情况下被确定,那么它就不会将变量标记为未使用,因为它可以确定构造函数会产生可观察到的副作用.

I've experienced similar issues myself, specifically when relying on constructors within template functions to produce side effects (for RAII, etc.). When Clang needs to know the template parameter passed in order to determine the constructor that was used, it naively treats the constructor as pure and marks the constructed variable unused (Wunused-variable), but if the constructor can be determined without instantiating the template, then it will not mark the variable unused because it can determine that the constructor produces an observable side-effect.

在您的情况下,由于模板仍然可能位于头文件中,因此是否标记为 static 都没有区别.使用类型特征库可能的实现"作为指导,并避免将这些模板值标记为 static 以避免诊断.

In your case, since it's likely that your template is in a header file anyway, it makes no difference whether it's marked static or not. Use the type traits library "possible implementations" as a guide and avoid marking these template values as static in order to avoid the diagnostic.

这篇关于C ++ Clang发出有关未使用的模板变量的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆