c++ - 为什么这个程序编译失败时会报错unreachable?

标签 c++ templates visual-c++

我正在为可变位大小像素颜色值创建一个类。无论如何,我让它工作了,但有一些奇怪的事情:

#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_tuint8_t 的情况并非如此

这是在 MSVC 上,有人知道为什么会发生这种情况吗?

最佳答案

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

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

my_typeuint32_ttarget_typeuint8_t 。所以,std::is_same<my_type, target_type>::valuefalse ,所以return *this;不会被执行。

但是,它会被编译!并且编译器报错,因为你肯定不能返回 *this (类型 c<uint32_t> ),在应该返回 c<uint8_t> 的函数中,因为它们是不同的类型...

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

关于c++ - 为什么这个程序编译失败时会报错unreachable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474623/

相关文章:

c++ - 如何正确序列化线程访问控制循环的标志

java - 使用双数组的最佳实践

c++ - 在结构具有该成员时访问模板函数中的结构成员

c++ - Lambda`s internal this in c++

c++ - 如何让我的应用程序不链接到某些库? `QT -= ` ?

perl - 将 Perl CGI 迁移到模板工具包的策略?

c++ - 使用 boost.python 导出 C++ 多态函数的聪明方法

c++ - 如何在 STL 容器中存储模板化异构对象

c++ - 使用 SSL_read() 时如何知道何时没有从服务器接收的进一步响应

C++ 重载运算符 double * Vec