首页 > 解决方案 > 检查类型的相等性

问题描述

我有一个结构和模板类,其中有一个函数应该检查 T 是否等于该结构,如果是,则执行某些操作。

结构:

struct mystruct
{
    int x;
    int y;
    int z;    
};

模板类:

template <typename T>
class myclass
{
    public:
    void myfunc()
    {
        // this condition is ignored..
        if(std::is_same<T,mystruct>::value==0)
        {
             cout << "T is not mystruct type" << '\n';

        }
        else
        {
            T ms;
            ms.x = 5;
            ms.y = 4;
            ms.z = 3;
        }
    }
};

在主函数中,如果 T == mystruct 一切正常:

int main()
{
    // no issues
   myclass<mystruct> x;
   x.myfunc();
}

但是如果 T != mystruct:

int main()
{
    //tries to unsuccessfuly convert int to mystruct
   myclass<int> x;
   x.myfunc();
}

执行失败并出现以下错误:

error: request for member 'x' in 'ms', which is of non-class type 'int'
             ms.x = 5;

有谁知道为什么 if-else 语句没有按预期工作?谢谢!

标签: c++templates

解决方案


即使if条件评估为false,对于特定模板实例化,整个模板仍然必须包含有效的 C++ 代码。

例如,如果模板的参数是int,那么语句的else部分if就等同于:

    else
    {
        int ms;
        ms.x = 5;
        ms.y = 4;
        ms.z = 3;
    }

为什么这不会编译应该很明显。因为整个模板就变成了,相当于:

    if (true)
    {
        cout << "T is not mystruct type" << '\n';
    }
    else
    {
        int ms;
        ms.x = 5;
        ms.y = 4;
        ms.z = 3;
    }

即使else永远不会被执行,它也必须是有效的 C++ 代码。模板也不例外。

引入的 C++17if constexpr要求评估的if表达式是常量,并且只有语句的适当部分if最终被编译,其余部分被有效地丢弃。因此,使用 C++17,您应该能够将if语句更改为if constexpr,并获得预期的结果。


推荐阅读