错误无法到达时,为什么该程序无法编译?

用户81993

我正在为可变位大小的像素颜色值创建一个类。无论如何,我都能正常工作,但是有些奇怪:

#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上,有人知道为什么会这样吗?

jpo38

就您而言,当您这样做时:

if (std::is_same<my_type, target_type>::value) {
    return *this;
}

my_typeuint32_t并且target_typeuint8_t所以std::is_same<my_type, target_type>::valuefalse,因此return *this;将不会执行。

但是,它将被编译而且编译器会报告错误,因为您肯定不能在应该返回a的函数中返回*this(type c<uint32_t>c<uint8_t>,因为它们是不同的类型...

模板函数的每个路径都必须对编译有效,即使其中某些路径受到保护,也可以防止运行时执行...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么Java编译器不会为无法到达的then语句产生无法到达的语句错误?

Java为什么会有“无法到达的语句”编译器错误?

该程序显示编译时错误..(Integer it:arr)的类型非法启动,为什么显示错误?

为什么该程序无法打印?

为什么该程序无法捕获异常?

为什么ld无法链接该程序?

为什么该程序无法正常工作?

为什么此等效程序无法编译?

为什么在编译该程序集时出现以下错误?

为什么会出现此“无法到达的语句”错误?

由于无法到达的语句,该代码无法编译

为什么无法编译?

运行此程序时出现“无法到达的代码错误”,但我不知道为什么

为什么下载依赖时我的flutter应用程序无法编译?

为什么该程序似乎无法正确融合?

为什么该程序无法访问子节点?

为什么该程序无法使用goroutine打印任何内容?

为什么程序无法正确计算该值?

为什么该程序无法打印所需的输出?

为什么该程序中的scanf()无法获取输入?

为什么该程序无法在我的文件上打印?

该程序为什么无法比较用户输入和文件?

为什么该程序的相等值无法打印?

为什么使用-threaded编译时,该Haskell程序为什么执行起来很奇怪?

为什么我的程序无法在Windows 7法语下编译?

为什么Linux编译程序无法在Windows上运行

为什么此Java 8程序无法编译?

为什么此部分应用程序无法编译?

为什么 CoreRT 编译的程序无法处理 ZIP 文件?