更明确地说,编译器是否应该处理 true_type
值为 true
在 enable_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 typeT
, 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/