我正在为可变位大小像素颜色值创建一个类。无论如何,我让它工作了,但有一些奇怪的事情:
#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;
不会被执行。
但是,它会被编译!并且编译器报错,因为你肯定不能返回 *this
(类型 c<uint32_t>
),在应该返回 c<uint8_t>
的函数中,因为它们是不同的类型...
模板函数的每个路径都必须对编译有效,即使其中一些路径受到保护以防止运行时执行...
关于c++ - 为什么这个程序编译失败时会报错unreachable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474623/