编译器在构建期间不断分配不兼容的类型。
错误信息:
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
在本例中,我将 T 模板设置为“int”
有谁知道为什么会发生这种情况或者是否有解决方法。
问题是,即使您将模板参数指定为int
, those else
部件必须在编译时实例化。
您可以申请构造函数 If https://en.cppreference.com/w/cpp/language/if#Constexpr_If(自 C++17 起)。
如果值为true
,则丢弃statement-false(如果存在),否则丢弃statement-true。
e.g.
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)