为什么当错误无法访问时,该程序无法编译
Why does this program fail to compile when the error is unreachable?
我正在为可变位大小的像素颜色值创建一个类。无论如何,我让它工作,但有一些奇怪的东西:
#pragma pack(push, 1)
template <typename my_type>
struct c {
my_type x;
c() {}
c(my_type x) { this->x = x; }
template<typename target_type>
c<target_type> convert() {
if (std::is_same<my_type, target_type>::value) {
return *this; //<- doesn't work
return *reinterpret_cast<c<target_type>*>(this); //<- does work
}
int target_size = sizeof(((c<target_type>*)0)->x);
int my_size = sizeof(x);
if (my_size < target_size) {
return c<target_type>(x << (target_size - my_size) * 8);
}
my_type rounder = ((x >> (my_size - target_size) * 8 - 1) & 9) > 4;
return c<target_type>((x >> (my_size - target_size) * 8) + rounder);
}
};
#pragma pack(pop)
在我标记的行上,我应该能够只返回*this,但是如果我这样做并尝试使用以下测试进行编译:
c<uint8_t> a;
c<uint32_t> b(2147483647);
a = b.convert<uint8_t>();
然后我得到错误
cannot convert from c<uint32_t> to c<uint8_t>
这是没有意义的,因为如果它是相同的类型,它不应该转换任何东西,而uint32_t
不是这种情况uint8_t
这是在MSVC上,有谁知道为什么会这样?
在您的情况下,当您这样做时:
if (std::is_same<my_type, target_type>::value) {
return *this;
}
my_type
是uint32_t
,target_type
是uint8_t
。因此,std::is_same<my_type, target_type>::value
false
,因此不会执行return *this;
。
但是,它将被编译!并且编译器报告错误,因为您绝对无法在应该返回c<uint8_t>
的函数中返回*this
(类型 c<uint32_t>
(,因为它们是不同的类型......
模板函数的每个路径都必须对编译有效,即使其中一些路径受到运行时执行保护......
在这种情况下,您需要的是函数的两个版本,一个用于同一类型,另一个用于其他类型。一种可能性:
template<typename target_type>
typename std::enable_if<std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
return *this;
}
template<typename target_type>
typename std::enable_if<!std::is_same<my_type, target_type>::value, c<target_type> >::type
convert() {
int target_size = sizeof(((c<target_type>*)0)->x);
int my_size = sizeof(x);
if (my_size < target_size) {
return c<target_type>(x << (target_size - my_size) * 8);
}
my_type rounder = ((x >> (my_size - target_size) * 8 - 1) & 9) > 4;
return c<target_type>((x >> (my_size - target_size) * 8) + rounder);
}
其工作原理是,std::enable_if
在类型相同的情况下启用第一个函数,在类型不同时启用所有其他函数
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- C ++程序编译错误,找不到/访问文件
- C++程序编译没有问题,但无法运行
- Mongdb C++ 驱动程序编译错误 for document{}.
- 添加类型名会导致程序编译失败
- 将 C 程序更改为 C++ 程序 - 编译错误
- 程序编译,但当分解为函数时实际上不会移动电机
- 如何链接 glib-2.0 库进行 c/c++ 程序编译
- 为什么 gcc 和 clang 为我的程序编译为不同的"const"结果?
- 复数程序编译时的计算方法错误
- qt 命令行应用程序编译
- 程序编译和运行,但一段时间后,它停止使用Typedef关键字在CPP上工作
- QML应用程序编译一个 *form.ui.qml文件,但忽略了关联的.qml文件
- 为什么该程序编译但不显示任何输出
- 分割故障程序编译为共享库,但不静态
- 程序编译,但我认为开关被忽略
- 程序编译后崩溃
- 什么是程序编译中的PIC级别
- 尽管使用不存在的成员,但程序编译
- C++程序编译在 Ubuntu 中失败,但在 MacOSX 中工作