编译器错误`在if语句中分配不兼容的类型` [英] Compiler error `assigning incompatible type within if statement`

查看:145
本文介绍了编译器错误`在if语句中分配不兼容的类型`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构建期间,编译器会不断分配不兼容的类型.

The compiler keeps assigning incompatible types during the build.

错误消息:

error: assigning to 'int' from incompatible type 'QString'
typeduserproperty.cpp:115:28: note: in instantiation of member function 'core::TypedUserProperty<int>::setValue' requested here

示例代码

 /**
  * @brief setValue
  * set value to property
  * @param val
  * value to set to property
  * @return
  * true - successfully set value
  * false - invalid value
  */
template<class T>
void TypedUserProperty<T>::setValue(QVariant val)
{

   if (std::is_same<T, int>::value == true) 
   {
      this->_value = val.toInt();
   }
   else if (std::is_same<T, QString>::value == true)
   {
      this->_value = val.toString();
   }
   else if (std::is_same<T, double>::value == true)
   {
      this->_value = val.toDouble();
   }
}

this->_value = val.toString();是发生错误的行

"_ value"是数据类型模板T

"_value" is data type template T

在这种情况下,我将T模板设置为'int'

in this case i'm setting the T Template as an 'int'

没有人知道为什么会这样或是否有解决方法.

does anyone know why this is occuring or if theres a workaround.

推荐答案

问题是,即使您将模板参数指定为int,那些else部分也必须在编译时实例化.

The problem is, even if you specify the template argument as int, those else parts have to be instantiated at compile-time.

您可以应用 Constexpr If (自C ++ 17开始)

You can apply Constexpr If (since C++17).

如果值为true,则丢弃statement-false(如果存在),否则,丢弃statement-true.

If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

例如

if constexpr (std::is_same<T,int>::value == true) {
    this->_value = val.toInt();
} else if constexpr (std::is_same<T,QString>::value == true) {
    this->_value = val.toString();
} else if constexpr (std::is_same<T,double>::value == true){
    this->_value = val.toDouble();
}

这篇关于编译器错误`在if语句中分配不兼容的类型`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆