c++ - 跨编译器的诊断不一致,以缩小非类型模板参数中的转换范围

标签 c++ c++11 templates language-lawyer non-type

template <bool>
void f() { }

int main ()
{
    constexpr long long int num = 5;
    f<num & 4>(); // bitwise & is intended
    return 0;
}

gcc 9 有一个问题:

error: no matching function for call to 'f<(5 & 4)>()'
error: narrowing conversion of '4' from 'long long int' to 'bool' [-Wnarrowing]

clang 有问题:

error: no matching function for call to 'f'

gcc 8 和 msvc 编译没有错误。

谁是正确的?我认为错误是正确的,但想确认一下。

最佳答案

这是格式错误的,因为 template non-type argument ,

The template argument that can be used with a non-type template parameter can be any converted constant expression of the type of the template parameter.

并且狭义转换不被视为 converted constant expression .

A converted constant expression of type T is an expression implicitly converted to type T, where the converted expression is a constant expression, and the implicit conversion sequence contains only:

  • ...
  • non-narrowing integral conversions
  • ...

关于c++ - 跨编译器的诊断不一致,以缩小非类型模板参数中的转换范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63324200/

相关文章:

c++ - 将整数数组转换为字符串

c++ - 动态加载库中的静态 C++ 对象是否在 dlopen() 返回之前初始化?

c++ - C++ 中的正则表达式

c++ - 序列化模板化子类

c# - C++ 等同于 C# 的 Func<T, TResult>

c++ - 错误 : template argument required for 'struct List'

java - 模板中所有 boolean 值的速度条件相同

c++ - 如何在 C++ 中通过函数名 (std::string) 调用函数?

c++ - 根据 c-tor 的特定条件选择要初始化的变量?

C++ 绑定(bind)返回类型模板参数