c++ - 隐式转换应该在模板参数的上下文中工作吗?

标签 c++ templates language-lawyer implicit-conversion non-type

更明确地说,编译器是否应该处理 true_type值为 trueenable_if 的第一个参数中,因为true_type真是std::integral_constant<bool, true> ,和integral_constant定义类型转换函数operator value_type

以下是最简单的测试代码:

#include <type_traits>

template <typename T>
std::enable_if_t<std::is_pod<T>{}>
test(T)
{
}

int main()
{
    test(true);
}

它被 GCC 和 Clang 接受,但被 MSVC 拒绝(直到 Visual Studio 2019 v16.3.1)。

最佳答案

您的代码格式正确,converted constant expression应考虑 non-type template parameter .

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.

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:

  • constexpr user-defined conversions (so a class can be used where integral type is expected)

std::is_pod 的转换运算符继承自 std::integral_constant constexpr用户定义的转换,然后转换后的 bool来自std::is_pod是转换后的常量表达式,可以应用。

<小时/>

作为解决方法(我想您已经意识到),您可以使用 std::is_pod_v<T> (C++17 起)或 std::is_pod_v<T>::value相反。

关于c++ - 隐式转换应该在模板参数的上下文中工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59512017/

相关文章:

python - 你在哪里存储 jinja 中的变量?

c++ - 数据成员的编译时多态性

c++ - 为什么编译器在这种情况下会选择不正确的函数重载?

c++ - 将 2 个十六进制值组合成 1 个十六进制值

c++ - SGE 中 SGI 机器上的 CPU 负载失控

java - 从 EXE 和 DLL 访问 Singleton 对象中的成员变量

c++ - 如何使用隐式模板类型推导

c++ - 从 VS 2012 开始在 Windows 和 Win XP 上运行 C++ 应用程序的要求

c - ISO C95 数组初始化保证

c++ - 动态分配的对象是否默认初始化?