c++ - 检查类型的相等性
问题描述
我有一个结构和模板类,其中有一个函数应该检查 T 是否等于该结构,如果是,则执行某些操作。
结构:
struct mystruct
{
int x;
int y;
int z;
};
模板类:
template <typename T>
class myclass
{
public:
void myfunc()
{
// this condition is ignored..
if(std::is_same<T,mystruct>::value==0)
{
cout << "T is not mystruct type" << '\n';
}
else
{
T ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
}
};
在主函数中,如果 T == mystruct 一切正常:
int main()
{
// no issues
myclass<mystruct> x;
x.myfunc();
}
但是如果 T != mystruct:
int main()
{
//tries to unsuccessfuly convert int to mystruct
myclass<int> x;
x.myfunc();
}
执行失败并出现以下错误:
error: request for member 'x' in 'ms', which is of non-class type 'int'
ms.x = 5;
有谁知道为什么 if-else 语句没有按预期工作?谢谢!
解决方案
即使if
条件评估为false
,对于特定模板实例化,整个模板仍然必须包含有效的 C++ 代码。
例如,如果模板的参数是int
,那么语句的else
部分if
就等同于:
else
{
int ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
为什么这不会编译应该很明显。因为整个模板就变成了,相当于:
if (true)
{
cout << "T is not mystruct type" << '\n';
}
else
{
int ms;
ms.x = 5;
ms.y = 4;
ms.z = 3;
}
即使else
永远不会被执行,它也必须是有效的 C++ 代码。模板也不例外。
引入的 C++17if constexpr
要求评估的if
表达式是常量,并且只有语句的适当部分if
最终被编译,其余部分被有效地丢弃。因此,使用 C++17,您应该能够将if
语句更改为if constexpr
,并获得预期的结果。
推荐阅读
- tensorflow - `get_variable()` 中的 `tf.zeros_initializer` 有什么问题?
- excel - 如何在文件更新时运行 Excel 宏?
- mysql - 如何根据执行时间进行选择
- javascript - 至尊机器人上的无限循环
- elasticsearch - Elasticsearch:我可以聚合并获取在每个存储桶中找到的范围/“最低”和“最高”ips 吗?
- spring-boot - IDP 使用未签名的 LogoutRequest 发起 SingleLogout
- azure - Azure - 创建新目录 - 关于这样做的权限的问题
- python - 在 tf.keras.Model 中获取输入形状(命令式 API)
- android - Android SSL 错误,afwlocalproxy MITM?
- vba - 根据 Access 数据库中的表检索登录用户名和输出首字母