为什么模板功能中的std :: iS_array没有区分int和数组类型?
在以下代码中,我使用模板功能和类型特征来区分整数类型(else情况)和数组类型。我希望输出分别为和array
,而是我获得了int
int ,并带有两个调用使用INT类型和数组类型分别实例化模板函数:
为什么?
#include <iostream>
#include <array>
template <typename T>
inline static void constexpr SetCoordinates()
{
if (std::is_array<T>::value)
std::cout<<"array\n";
else
std::cout<<"int\n";
}
int main()
{
int a = 6;
std::array<int, 4> arr = {1,2,3,4};
SetCoordinates<decltype(a)>();
SetCoordinates<decltype(arr)>();
return 0;
}
In the following code, I am using a template function and type traits to distinguish between an integer type (else case) and array type. I would expect the output to be int
and array
respectively, instead I get int
int
with the two calls that instantiates the template functions respectively with an int type and an array type:
Why is that?
#include <iostream>
#include <array>
template <typename T>
inline static void constexpr SetCoordinates()
{
if (std::is_array<T>::value)
std::cout<<"array\n";
else
std::cout<<"int\n";
}
int main()
{
int a = 6;
std::array<int, 4> arr = {1,2,3,4};
SetCoordinates<decltype(a)>();
SetCoordinates<decltype(arr)>();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std :: is_array
不包括情况std ::数组
;相反,它仅检查类型是否只是普通数组类型(即t []
,t [n]
)。因此,如果您的语句降落在错误的分支中,则您的。
您必须为
std :: Array
提供一个自定义特征,以实现:查看演示
The
std::is_array
does not include the case ofstd::array
; Rather, it only checks if the type is just a normal array type(i.eT[]
,T[N]
). Hence, yourif
statement lands in the false branch.You have to provide a custom traits for the
std::array
for this to happen:See a demo
在这种简单的情况下,我可以使用
std :: IS_Integral
,提供模板函数仅使用这两种类型来调用:In this simple case I can use
std::is_integral
, providing the template function is called only with those two types: