我正在为可变位大小的像素颜色值创建一个类。无论如何,我都能正常工作,但是有些奇怪:
#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;
将不会执行。
但是,它将被编译!而且编译器会报告错误,因为您肯定不能在应该返回a的函数中返回*this
(type c<uint32_t>
)c<uint8_t>
,因为它们是不同的类型...
模板函数的每个路径都必须对编译有效,即使其中某些路径受到保护,也可以防止运行时执行...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句